blob: 20687e91a887e992c923a416b7ac11a4bcabd10a [file] [log] [blame]
[email protected]9045b8822012-01-13 20:35:351// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit586acc5fe2008-07-26 22:42:524
[email protected]ea224582008-12-07 20:25:465#include "build/build_config.h"
6
[email protected]9396b252008-09-29 17:29:387#if defined(OS_WIN)
[email protected]d8eb84242010-09-25 02:25:068#include <windows.h>
[email protected]aa84a7e2012-03-15 21:29:069#include <shlobj.h>
[email protected]9396b252008-09-29 17:29:3810#endif
11
initial.commit586acc5fe2008-07-26 22:42:5212#include <algorithm>
initial.commit586acc5fe2008-07-26 22:42:5213
[email protected]aad63572011-05-24 20:14:3914#include "base/basictypes.h"
[email protected]218aa6a12011-09-13 17:38:3815#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5816#include "base/compiler_specific.h"
thestigd8df0332014-09-04 06:33:2917#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0718#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2819#include "base/format_macros.h"
mmenke19378d22014-09-09 04:12:5920#include "base/memory/scoped_ptr.h"
[email protected]084262c2011-12-01 21:12:4721#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2222#include "base/message_loop/message_loop.h"
[email protected]255620da2013-08-19 13:14:2923#include "base/message_loop/message_loop_proxy.h"
initial.commit586acc5fe2008-07-26 22:42:5224#include "base/path_service.h"
[email protected]255620da2013-08-19 13:14:2925#include "base/run_loop.h"
[email protected]4dc3ad4f2013-06-11 07:15:5026#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5527#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2228#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2229#include "base/strings/string_util.h"
30#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0531#include "base/strings/utf_string_conversions.h"
mmenkecbc2b712014-10-09 20:29:0732#include "net/base/chunked_upload_data_stream.h"
33#include "net/base/elements_upload_data_stream.h"
initial.commit586acc5fe2008-07-26 22:42:5234#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2535#include "net/base/load_timing_info.h"
36#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0637#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5238#include "net/base/net_module.h"
39#include "net/base/net_util.h"
[email protected]2ca01e52013-10-31 22:05:1940#include "net/base/request_priority.h"
[email protected]42fdb452012-11-01 12:44:4041#include "net/base/test_data_directory.h"
[email protected]f288ef02012-12-15 20:28:2842#include "net/base/upload_bytes_element_reader.h"
43#include "net/base/upload_data_stream.h"
44#include "net/base/upload_file_element_reader.h"
[email protected]6e7845ae2013-03-29 21:48:1145#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2446#include "net/cert/mock_cert_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1147#include "net/cert/test_root_certs.h"
eromaned744f32015-04-09 06:35:4948#include "net/cert_net/nss_ocsp.h"
[email protected]aa84a7e2012-03-15 21:29:0649#include "net/cookies/cookie_monster.h"
50#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5251#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5352#include "net/dns/mock_host_resolver.h"
[email protected]ba2f3342009-07-30 18:08:4253#include "net/ftp/ftp_network_layer.h"
[email protected]b7572ea2013-11-26 20:16:3854#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5255#include "net/http/http_cache.h"
56#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1957#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2558#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2159#include "net/http/http_response_headers.h"
[email protected]e50efea2014-03-24 18:41:0060#include "net/http/http_util.h"
eroman87c53d62015-04-02 06:51:0761#include "net/log/net_log.h"
vishal.b62985ca92015-04-17 08:45:5162#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4663#include "net/log/test_net_log_entry.h"
64#include "net/log/test_net_log_util.h"
[email protected]63de95b2008-12-10 04:11:2765#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1966#include "net/socket/ssl_client_socket.h"
davidben8ecc3072014-09-03 23:19:0967#include "net/ssl/ssl_cipher_suite_names.h"
[email protected]536fd0b2013-03-14 17:41:5768#include "net/ssl/ssl_connection_status_flags.h"
[email protected]6e7845ae2013-03-29 21:48:1169#include "net/test/cert_test_util.h"
[email protected]89b32522013-05-07 20:04:2170#include "net/test/spawned_test_server/spawned_test_server.h"
[email protected]e0f35c92013-05-08 16:04:3471#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4372#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5273#include "net/url_request/url_request.h"
[email protected]bcb84f8b2009-08-31 16:20:1474#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:5075#include "net/url_request/url_request_intercepting_job_factory.h"
76#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:4977#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5178#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4779#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4480#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5281#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1582#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:5283
[email protected]02494ec2014-05-07 15:05:2984#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:5585#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:2986#include "net/url_request/file_protocol_handler.h"
87#include "net/url_request/url_request_file_dir_job.h"
88#endif
89
90#if !defined(DISABLE_FTP_SUPPORT)
91#include "net/url_request/ftp_protocol_handler.h"
92#endif
93
[email protected]dffe8242012-03-20 15:14:2794#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:4895#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:5696#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:2797#include "base/win/windows_version.h"
98#endif
99
[email protected]ad65a3e2013-12-25 18:18:01100using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33101using base::Time;
halton.huoe4e45742014-12-08 07:55:46102using std::string;
[email protected]e1acf6f2008-10-27 20:43:33103
[email protected]7461a402011-03-24 23:19:51104namespace net {
105
initial.commit586acc5fe2008-07-26 22:42:52106namespace {
107
[email protected]42cba2fb2013-03-29 19:58:57108const base::string16 kChrome(ASCIIToUTF16("chrome"));
109const base::string16 kSecret(ASCIIToUTF16("secret"));
110const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44111
[email protected]2bba3252013-04-08 19:50:59112// Tests load timing information in the case a fresh connection was used, with
113// no proxy.
[email protected]cba24642014-08-15 20:49:59114void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25115 int connect_timing_flags) {
116 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59117 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25118
119 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
120 EXPECT_FALSE(load_timing_info.request_start.is_null());
121
122 EXPECT_LE(load_timing_info.request_start,
123 load_timing_info.connect_timing.connect_start);
124 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
125 connect_timing_flags);
126 EXPECT_LE(load_timing_info.connect_timing.connect_end,
127 load_timing_info.send_start);
128 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
129 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
130
[email protected]58e32bb2013-01-21 18:23:25131 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
132 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
133}
134
[email protected]2bba3252013-04-08 19:50:59135// Same as above, but with proxy times.
136void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59137 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59138 int connect_timing_flags) {
139 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59140 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59141
142 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
143 EXPECT_FALSE(load_timing_info.request_start.is_null());
144
145 EXPECT_LE(load_timing_info.request_start,
146 load_timing_info.proxy_resolve_start);
147 EXPECT_LE(load_timing_info.proxy_resolve_start,
148 load_timing_info.proxy_resolve_end);
149 EXPECT_LE(load_timing_info.proxy_resolve_end,
150 load_timing_info.connect_timing.connect_start);
151 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
152 connect_timing_flags);
153 EXPECT_LE(load_timing_info.connect_timing.connect_end,
154 load_timing_info.send_start);
155 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
156 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
157}
158
159// Same as above, but with a reused socket and proxy times.
160void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59161 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59162 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59163 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59164
165 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
166 EXPECT_FALSE(load_timing_info.request_start.is_null());
167
168 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
169
170 EXPECT_LE(load_timing_info.request_start,
171 load_timing_info.proxy_resolve_start);
172 EXPECT_LE(load_timing_info.proxy_resolve_start,
173 load_timing_info.proxy_resolve_end);
174 EXPECT_LE(load_timing_info.proxy_resolve_end,
175 load_timing_info.send_start);
176 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
177 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
178}
179
xunjielia6888202015-04-14 21:34:25180#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25181// Tests load timing information in the case of a cache hit, when no cache
182// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17183base::StringPiece TestNetResourceProvider(int key) {
184 return "header";
185}
186
187void FillBuffer(char* buffer, size_t len) {
188 static bool called = false;
189 if (!called) {
190 called = true;
191 int seed = static_cast<int>(Time::Now().ToInternalValue());
192 srand(seed);
193 }
194
195 for (size_t i = 0; i < len; i++) {
196 buffer[i] = static_cast<char>(rand());
197 if (!buffer[i])
198 buffer[i] = 'g';
199 }
200}
xunjielia6888202015-04-14 21:34:25201#endif
[email protected]e3a85452013-11-14 01:46:17202
203#if !defined(OS_IOS)
[email protected]3b23a222013-05-15 21:33:25204void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59205 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25206 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59207 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25208
209 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
210 EXPECT_FALSE(load_timing_info.request_start.is_null());
211
212 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
213 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
214 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
215 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
216
217 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
218 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
219}
220
xunjielia6888202015-04-14 21:34:25221#if !defined(DISABLE_FTP_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25222// Tests load timing in the case that there is no HTTP response. This can be
223// used to test in the case of errors or non-HTTP requests.
224void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59225 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25226 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59227 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25228
229 // Only the request times should be non-null.
230 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
231 EXPECT_FALSE(load_timing_info.request_start.is_null());
232
233 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
234
235 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
236 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
237 EXPECT_TRUE(load_timing_info.send_start.is_null());
238 EXPECT_TRUE(load_timing_info.send_end.is_null());
239 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
240}
xunjielia6888202015-04-14 21:34:25241#endif
[email protected]58e32bb2013-01-21 18:23:25242
[email protected]71c64f62008-11-15 04:36:51243// Do a case-insensitive search through |haystack| for |needle|.
244bool ContainsString(const std::string& haystack, const char* needle) {
245 std::string::const_iterator it =
246 std::search(haystack.begin(),
247 haystack.end(),
248 needle,
249 needle + strlen(needle),
[email protected]07f1cee2010-11-03 03:53:35250 base::CaseInsensitiveCompare<char>());
[email protected]71c64f62008-11-15 04:36:51251 return it != haystack.end();
252}
253
mmenkecbc2b712014-10-09 20:29:07254scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
[email protected]f288ef02012-12-15 20:28:28255 scoped_ptr<UploadElementReader> reader(
256 new UploadBytesElementReader(data, strlen(data)));
mmenkecbc2b712014-10-09 20:29:07257 return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23258}
259
[email protected]96adadb2010-08-28 01:16:17260// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51261void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17262 // -1 means unknown. 0 means no encryption.
263 EXPECT_GT(ssl_info.security_bits, 0);
264
265 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
pkasting6b68a162014-12-01 22:10:29266 uint16 cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17267 ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29268 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17269}
270
[email protected]79e1fd62013-06-20 06:50:04271void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
272 const GURL& host_url) {
273 std::string sent_value;
274
275 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
276 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
277
278 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
279 EXPECT_EQ("keep-alive", sent_value);
280}
281
[email protected]ede03212012-09-07 12:52:26282bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27283 size_t size = a.size();
284
285 if (size != b.size())
286 return false;
287
288 for (size_t i = 0; i < size; ++i) {
289 if (!a[i].Equals(b[i]))
290 return false;
291 }
292
293 return true;
294}
[email protected]e3a85452013-11-14 01:46:17295#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27296
[email protected]dc5a5cf2012-09-26 02:49:30297// A network delegate that allows the user to choose a subset of request stages
298// to block in. When blocking, the delegate can do one of the following:
299// * synchronously return a pre-specified error code, or
300// * asynchronously return that value via an automatically called callback,
301// or
302// * block and wait for the user to do a callback.
303// Additionally, the user may also specify a redirect URL -- then each request
304// with the current URL different from the redirect target will be redirected
305// to that target, in the on-before-URL-request stage, independent of whether
306// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12307class BlockingNetworkDelegate : public TestNetworkDelegate {
308 public:
[email protected]dc5a5cf2012-09-26 02:49:30309 // Stages in which the delegate can block.
310 enum Stage {
[email protected]9045b8822012-01-13 20:35:35311 NOT_BLOCKED = 0,
312 ON_BEFORE_URL_REQUEST = 1 << 0,
313 ON_BEFORE_SEND_HEADERS = 1 << 1,
314 ON_HEADERS_RECEIVED = 1 << 2,
315 ON_AUTH_REQUIRED = 1 << 3
316 };
317
[email protected]dc5a5cf2012-09-26 02:49:30318 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59319 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30320 enum BlockMode {
321 SYNCHRONOUS, // No callback, returns specified return values.
322 AUTO_CALLBACK, // |this| posts a task to run the callback using the
323 // specified return codes.
324 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
325 // |auth_retval_| are ignored. In every blocking stage the
326 // message loop is quit.
327 };
328
329 // Creates a delegate which does not block at all.
330 explicit BlockingNetworkDelegate(BlockMode block_mode);
331
332 // For users to trigger a callback returning |response|.
333 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
334 // Only call if |block_mode_| == USER_CALLBACK.
335 void DoCallback(int response);
336 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
337
338 // Setters.
339 void set_retval(int retval) {
340 ASSERT_NE(USER_CALLBACK, block_mode_);
341 ASSERT_NE(ERR_IO_PENDING, retval);
342 ASSERT_NE(OK, retval);
343 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35344 }
345
[email protected]dc5a5cf2012-09-26 02:49:30346 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
347 // |auth_credentials_| will be passed with the response.
348 void set_auth_retval(AuthRequiredResponse auth_retval) {
349 ASSERT_NE(USER_CALLBACK, block_mode_);
350 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
351 auth_retval_ = auth_retval;
352 }
353 void set_auth_credentials(const AuthCredentials& auth_credentials) {
354 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35355 }
356
[email protected]dc5a5cf2012-09-26 02:49:30357 void set_redirect_url(const GURL& url) {
358 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35359 }
360
[email protected]dc5a5cf2012-09-26 02:49:30361 void set_block_on(int block_on) {
362 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35363 }
364
[email protected]dc5a5cf2012-09-26 02:49:30365 // Allows the user to check in which state did we block.
366 Stage stage_blocked_for_callback() const {
367 EXPECT_EQ(USER_CALLBACK, block_mode_);
368 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35369 }
370
371 private:
[email protected]dc5a5cf2012-09-26 02:49:30372 void RunCallback(int response, const CompletionCallback& callback);
373 void RunAuthCallback(AuthRequiredResponse response,
374 const AuthCallback& callback);
375
[email protected]9045b8822012-01-13 20:35:35376 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20377 int OnBeforeURLRequest(URLRequest* request,
378 const CompletionCallback& callback,
379 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35380
dchengb03027d2014-10-21 12:00:20381 int OnBeforeSendHeaders(URLRequest* request,
382 const CompletionCallback& callback,
383 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35384
dchengb03027d2014-10-21 12:00:20385 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35386 URLRequest* request,
387 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32388 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16389 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13390 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35391
dchengb03027d2014-10-21 12:00:20392 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35393 URLRequest* request,
394 const AuthChallengeInfo& auth_info,
395 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13396 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35397
[email protected]dc5a5cf2012-09-26 02:49:30398 // Resets the callbacks and |stage_blocked_for_callback_|.
399 void Reset();
[email protected]9045b8822012-01-13 20:35:35400
[email protected]dc5a5cf2012-09-26 02:49:30401 // Checks whether we should block in |stage|. If yes, returns an error code
402 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
403 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
404
405 // Configuration parameters, can be adjusted by public methods:
406 const BlockMode block_mode_;
407
408 // Values returned on blocking stages when mode is SYNCHRONOUS or
409 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
410 int retval_; // To be returned in non-auth stages.
411 AuthRequiredResponse auth_retval_;
412
[email protected]5f714132014-03-26 10:41:16413 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30414 int block_on_; // Bit mask: in which stages to block.
415
416 // |auth_credentials_| will be copied to |*target_auth_credential_| on
417 // callback.
418 AuthCredentials auth_credentials_;
419 AuthCredentials* target_auth_credentials_;
420
421 // Internal variables, not set by not the user:
422 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
423 // USER_CALLBACK).
424 Stage stage_blocked_for_callback_;
425
426 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35427 CompletionCallback callback_;
428 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30429
430 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
431
432 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35433};
434
[email protected]dc5a5cf2012-09-26 02:49:30435BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
436 : block_mode_(block_mode),
437 retval_(OK),
438 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
439 block_on_(0),
440 target_auth_credentials_(NULL),
441 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32442 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30443}
444
445void BlockingNetworkDelegate::DoCallback(int response) {
446 ASSERT_EQ(USER_CALLBACK, block_mode_);
447 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
448 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
449 CompletionCallback callback = callback_;
450 Reset();
451 RunCallback(response, callback);
452}
453
454void BlockingNetworkDelegate::DoAuthCallback(
455 NetworkDelegate::AuthRequiredResponse response) {
456 ASSERT_EQ(USER_CALLBACK, block_mode_);
457 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
458 AuthCallback auth_callback = auth_callback_;
459 Reset();
460 RunAuthCallback(response, auth_callback);
461}
462
463void BlockingNetworkDelegate::RunCallback(int response,
464 const CompletionCallback& callback) {
465 callback.Run(response);
466}
467
468void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
469 const AuthCallback& callback) {
470 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
471 ASSERT_TRUE(target_auth_credentials_ != NULL);
472 *target_auth_credentials_ = auth_credentials_;
473 }
474 callback.Run(response);
475}
476
477int BlockingNetworkDelegate::OnBeforeURLRequest(
478 URLRequest* request,
479 const CompletionCallback& callback,
480 GURL* new_url) {
481 if (redirect_url_ == request->url())
482 return OK; // We've already seen this request and redirected elsewhere.
483
484 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
485
486 if (!redirect_url_.is_empty())
487 *new_url = redirect_url_;
488
489 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
490}
491
492int BlockingNetworkDelegate::OnBeforeSendHeaders(
493 URLRequest* request,
494 const CompletionCallback& callback,
495 HttpRequestHeaders* headers) {
496 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
497
498 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
499}
500
501int BlockingNetworkDelegate::OnHeadersReceived(
502 URLRequest* request,
503 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32504 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16505 scoped_refptr<HttpResponseHeaders>* override_response_headers,
506 GURL* allowed_unsafe_redirect_url) {
507 TestNetworkDelegate::OnHeadersReceived(request,
508 callback,
509 original_response_headers,
510 override_response_headers,
511 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30512
513 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
514}
515
516NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
517 URLRequest* request,
518 const AuthChallengeInfo& auth_info,
519 const AuthCallback& callback,
520 AuthCredentials* credentials) {
521 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
522 credentials);
523 // Check that the user has provided callback for the previous blocked stage.
524 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
525
526 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
527 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
528 }
529
530 target_auth_credentials_ = credentials;
531
532 switch (block_mode_) {
533 case SYNCHRONOUS:
534 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
535 *target_auth_credentials_ = auth_credentials_;
536 return auth_retval_;
537
538 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34539 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30540 FROM_HERE,
541 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
542 weak_factory_.GetWeakPtr(), auth_retval_, callback));
543 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
544
545 case USER_CALLBACK:
546 auth_callback_ = callback;
547 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
[email protected]2da659e2013-05-23 20:51:34548 base::MessageLoop::current()->PostTask(FROM_HERE,
549 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30550 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
551 }
552 NOTREACHED();
553 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
554}
555
556void BlockingNetworkDelegate::Reset() {
557 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
558 stage_blocked_for_callback_ = NOT_BLOCKED;
559 callback_.Reset();
560 auth_callback_.Reset();
561}
562
563int BlockingNetworkDelegate::MaybeBlockStage(
564 BlockingNetworkDelegate::Stage stage,
565 const CompletionCallback& callback) {
566 // Check that the user has provided callback for the previous blocked stage.
567 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
568
569 if ((block_on_ & stage) == 0) {
570 return OK;
571 }
572
573 switch (block_mode_) {
574 case SYNCHRONOUS:
575 EXPECT_NE(OK, retval_);
576 return retval_;
577
578 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34579 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30580 FROM_HERE,
581 base::Bind(&BlockingNetworkDelegate::RunCallback,
582 weak_factory_.GetWeakPtr(), retval_, callback));
583 return ERR_IO_PENDING;
584
585 case USER_CALLBACK:
586 callback_ = callback;
587 stage_blocked_for_callback_ = stage;
[email protected]2da659e2013-05-23 20:51:34588 base::MessageLoop::current()->PostTask(FROM_HERE,
589 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30590 return ERR_IO_PENDING;
591 }
592 NOTREACHED();
593 return 0;
594}
595
[email protected]d5a4dd62012-05-23 01:41:04596class TestURLRequestContextWithProxy : public TestURLRequestContext {
597 public:
598 // Does not own |delegate|.
599 TestURLRequestContextWithProxy(const std::string& proxy,
600 NetworkDelegate* delegate)
601 : TestURLRequestContext(true) {
602 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
603 set_network_delegate(delegate);
604 Init();
605 }
dchengb03027d2014-10-21 12:00:20606 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04607};
608
609} // namespace
610
[email protected]a592c0432012-12-01 18:10:29611// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48612class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00613 public:
[email protected]ef2bf422012-05-11 03:27:09614 URLRequestTest() : default_context_(true) {
615 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25616 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50617 job_factory_impl_ = new URLRequestJobFactoryImpl();
618 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50619 }
bengr1bf8e942014-11-07 01:36:50620
dcheng67be2b1f2014-10-27 21:47:29621 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18622 // URLRequestJobs may post clean-up tasks on destruction.
623 base::RunLoop().RunUntilIdle();
624 }
[email protected]87a09a92011-07-14 15:50:50625
dcheng2339883c2014-12-23 00:23:05626 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50627 SetUpFactory();
628 default_context_.set_job_factory(job_factory_.get());
629 default_context_.Init();
630 PlatformTest::SetUp();
631 }
632
633 virtual void SetUpFactory() {
634 job_factory_impl_->SetProtocolHandler("data", new DataProtocolHandler);
635#if !defined(DISABLE_FILE_SUPPORT)
636 job_factory_impl_->SetProtocolHandler(
637 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
638#endif
639 }
640
641 TestNetworkDelegate* default_network_delegate() {
642 return &default_network_delegate_;
643 }
644
645 const TestURLRequestContext& default_context() const {
646 return default_context_;
647 }
648
649
[email protected]3c5ca8c2011-09-29 01:14:51650 // Adds the TestJobInterceptor to the default context.
651 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23652 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
bengr1bf8e942014-11-07 01:36:50653 job_factory_impl_->SetProtocolHandler("http", NULL);
654 job_factory_impl_->SetProtocolHandler("http", protocol_handler_);
[email protected]f53b4802012-12-20 17:04:23655 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51656 }
657
[email protected]87a09a92011-07-14 15:50:50658 protected:
vishal.b62985ca92015-04-17 08:45:51659 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24660 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50661 URLRequestJobFactoryImpl* job_factory_impl_;
662 scoped_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09663 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48664};
665
[email protected]316c1e5e2012-09-12 15:17:44666TEST_F(URLRequestTest, AboutBlankTest) {
667 TestDelegate d;
668 {
[email protected]f7022f32014-08-21 16:32:19669 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36670 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44671
[email protected]f7022f32014-08-21 16:32:19672 r->Start();
673 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44674
[email protected]255620da2013-08-19 13:14:29675 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44676
[email protected]f7022f32014-08-21 16:32:19677 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44678 EXPECT_FALSE(d.received_data_before_response());
679 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19680 EXPECT_EQ("", r->GetSocketAddress().host());
681 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04682
683 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19684 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44685 }
686}
687
688TEST_F(URLRequestTest, DataURLImageTest) {
689 TestDelegate d;
690 {
691 // Use our nice little Chrome logo.
[email protected]f7022f32014-08-21 16:32:19692 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:19693 GURL(
davidben151423e2015-03-23 18:48:36694 "data:image/png;base64,"
695 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
696 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
697 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
698 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
699 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
700 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
701 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
702 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
703 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
704 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
705 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
706 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
707 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
708 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
709 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
710 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
711 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
712 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
713 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
714 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44715
[email protected]f7022f32014-08-21 16:32:19716 r->Start();
717 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44718
[email protected]255620da2013-08-19 13:14:29719 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44720
[email protected]f7022f32014-08-21 16:32:19721 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44722 EXPECT_FALSE(d.received_data_before_response());
723 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19724 EXPECT_EQ("", r->GetSocketAddress().host());
725 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04726
727 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19728 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44729 }
730}
731
[email protected]5ecf7cb282014-05-11 01:49:55732#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44733TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15734 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44735 PathService::Get(base::FILE_EXE, &app_path);
736 GURL app_url = FilePathToFileURL(app_path);
737
738 TestDelegate d;
739 {
davidben151423e2015-03-23 18:48:36740 scoped_ptr<URLRequest> r(
741 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44742
[email protected]f7022f32014-08-21 16:32:19743 r->Start();
744 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44745
[email protected]255620da2013-08-19 13:14:29746 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44747
748 int64 file_size = -1;
[email protected]56285702013-12-04 18:22:49749 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44750
[email protected]f7022f32014-08-21 16:32:19751 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44752 EXPECT_EQ(1, d.response_started_count());
753 EXPECT_FALSE(d.received_data_before_response());
754 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19755 EXPECT_EQ("", r->GetSocketAddress().host());
756 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04757
758 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19759 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44760 }
761}
762
[email protected]ba40bb762012-12-17 07:11:04763TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15764 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04765 PathService::Get(base::FILE_EXE, &app_path);
766 GURL app_url = FilePathToFileURL(app_path);
767
768 TestDelegate d;
769 {
davidben151423e2015-03-23 18:48:36770 scoped_ptr<URLRequest> r(
771 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04772
[email protected]f7022f32014-08-21 16:32:19773 r->Start();
774 EXPECT_TRUE(r->is_pending());
775 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04776 }
[email protected]79e1fd62013-06-20 06:50:04777 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04778 // destroyed.
[email protected]255620da2013-08-19 13:14:29779 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04780}
781
[email protected]316c1e5e2012-09-12 15:17:44782TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
783 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17784 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44785 FillBuffer(buffer.get(), buffer_size);
786
[email protected]6cdfd7f2013-02-08 20:40:15787 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52788 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44789 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30790 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44791
792 int64 file_size;
[email protected]56285702013-12-04 18:22:49793 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44794
795 const size_t first_byte_position = 500;
796 const size_t last_byte_position = buffer_size - first_byte_position;
797 const size_t content_length = last_byte_position - first_byte_position + 1;
798 std::string partial_buffer_string(buffer.get() + first_byte_position,
799 buffer.get() + last_byte_position + 1);
800
801 TestDelegate d;
802 {
davidben151423e2015-03-23 18:48:36803 scoped_ptr<URLRequest> r(
804 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44805
806 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38807 headers.SetHeader(
808 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59809 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38810 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19811 r->SetExtraRequestHeaders(headers);
812 r->Start();
813 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44814
[email protected]255620da2013-08-19 13:14:29815 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19816 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44817 EXPECT_EQ(1, d.response_started_count());
818 EXPECT_FALSE(d.received_data_before_response());
819 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
820 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
821 EXPECT_TRUE(partial_buffer_string == d.data_received());
822 }
823
[email protected]dd3aa792013-07-16 19:10:23824 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44825}
826
827TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
828 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17829 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44830 FillBuffer(buffer.get(), buffer_size);
831
[email protected]6cdfd7f2013-02-08 20:40:15832 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52833 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44834 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30835 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44836
837 int64 file_size;
[email protected]56285702013-12-04 18:22:49838 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44839
840 const size_t first_byte_position = 500;
841 const size_t last_byte_position = buffer_size - 1;
842 const size_t content_length = last_byte_position - first_byte_position + 1;
843 std::string partial_buffer_string(buffer.get() + first_byte_position,
844 buffer.get() + last_byte_position + 1);
845
846 TestDelegate d;
847 {
davidben151423e2015-03-23 18:48:36848 scoped_ptr<URLRequest> r(
849 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44850
851 HttpRequestHeaders headers;
852 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59853 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38854 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19855 r->SetExtraRequestHeaders(headers);
856 r->Start();
857 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44858
[email protected]255620da2013-08-19 13:14:29859 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19860 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44861 EXPECT_EQ(1, d.response_started_count());
862 EXPECT_FALSE(d.received_data_before_response());
863 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
864 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
865 EXPECT_TRUE(partial_buffer_string == d.data_received());
866 }
867
[email protected]dd3aa792013-07-16 19:10:23868 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44869}
870
871TEST_F(URLRequestTest, FileTestMultipleRanges) {
872 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17873 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44874 FillBuffer(buffer.get(), buffer_size);
875
[email protected]6cdfd7f2013-02-08 20:40:15876 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52877 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44878 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30879 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44880
881 int64 file_size;
[email protected]56285702013-12-04 18:22:49882 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44883
884 TestDelegate d;
885 {
davidben151423e2015-03-23 18:48:36886 scoped_ptr<URLRequest> r(
887 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44888
889 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38890 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19891 r->SetExtraRequestHeaders(headers);
892 r->Start();
893 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44894
[email protected]255620da2013-08-19 13:14:29895 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44896 EXPECT_TRUE(d.request_failed());
897 }
898
[email protected]dd3aa792013-07-16 19:10:23899 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44900}
901
[email protected]3ca8b362013-11-11 22:18:07902TEST_F(URLRequestTest, AllowFileURLs) {
903 base::ScopedTempDir temp_dir;
904 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
905 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52906 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07907 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:30908 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:59909 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:07910
911 {
912 TestDelegate d;
913 TestNetworkDelegate network_delegate;
914 network_delegate.set_can_access_files(true);
915 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36916 scoped_ptr<URLRequest> r(
917 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19918 r->Start();
[email protected]3ca8b362013-11-11 22:18:07919 base::RunLoop().Run();
920 EXPECT_FALSE(d.request_failed());
921 EXPECT_EQ(test_data, d.data_received());
922 }
923
924 {
925 TestDelegate d;
926 TestNetworkDelegate network_delegate;
927 network_delegate.set_can_access_files(false);
928 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36929 scoped_ptr<URLRequest> r(
930 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19931 r->Start();
[email protected]3ca8b362013-11-11 22:18:07932 base::RunLoop().Run();
933 EXPECT_TRUE(d.request_failed());
934 EXPECT_EQ("", d.data_received());
935 }
936}
937
[email protected]316c1e5e2012-09-12 15:17:44938
939TEST_F(URLRequestTest, FileDirCancelTest) {
940 // Put in mock resource provider.
941 NetModule::SetResourceProvider(TestNetResourceProvider);
942
943 TestDelegate d;
944 {
[email protected]6cdfd7f2013-02-08 20:40:15945 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:44946 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
947 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
948 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
949
[email protected]f7022f32014-08-21 16:32:19950 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36951 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19952 req->Start();
953 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44954
955 d.set_cancel_in_received_data_pending(true);
956
[email protected]255620da2013-08-19 13:14:29957 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44958 }
959
960 // Take out mock resource provider.
961 NetModule::SetResourceProvider(NULL);
962}
963
[email protected]5f9581402013-10-30 13:08:32964TEST_F(URLRequestTest, FileDirOutputSanity) {
965 // Verify the general sanity of the the output of the file:
966 // directory lister by checking for the output of a known existing
967 // file.
968 const char sentinel_name[] = "filedir-sentinel";
969
970 base::FilePath path;
971 PathService::Get(base::DIR_SOURCE_ROOT, &path);
972 path = path.Append(FILE_PATH_LITERAL("net"));
973 path = path.Append(FILE_PATH_LITERAL("data"));
974 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
975
976 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:19977 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36978 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19979 req->Start();
[email protected]5f9581402013-10-30 13:08:32980 base::RunLoop().Run();
981
982 // Generate entry for the sentinel file.
983 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:58984 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:49985 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:32986 EXPECT_GT(info.size, 0);
987 std::string sentinel_output = GetDirectoryListingEntry(
988 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
989 std::string(sentinel_name),
990 false /* is_dir */,
991 info.size,
992 info.last_modified);
993
994 ASSERT_LT(0, d.bytes_received());
995 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:19996 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:32997 // Check for the entry generated for the "sentinel" file.
998 const std::string& data = d.data_received();
999 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1000}
1001
[email protected]316c1e5e2012-09-12 15:17:441002TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1003 // There is an implicit redirect when loading a file path that matches a
1004 // directory and does not end with a slash. Ensure that following such
1005 // redirects does not crash. See http://crbug.com/18686.
1006
[email protected]6cdfd7f2013-02-08 20:40:151007 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441008 PathService::Get(base::DIR_SOURCE_ROOT, &path);
1009 path = path.Append(FILE_PATH_LITERAL("net"));
1010 path = path.Append(FILE_PATH_LITERAL("data"));
1011 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1012
1013 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191014 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361015 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191016 req->Start();
[email protected]255620da2013-08-19 13:14:291017 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441018
1019 ASSERT_EQ(1, d.received_redirect_count());
1020 ASSERT_LT(0, d.bytes_received());
1021 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191022 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441023}
1024
1025#if defined(OS_WIN)
1026// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1027TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1028 TestDelegate d;
davidben151423e2015-03-23 18:48:361029 scoped_ptr<URLRequest> req(
1030 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191031 req->Start();
[email protected]255620da2013-08-19 13:14:291032 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441033
1034 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191035 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441036}
[email protected]5ecf7cb282014-05-11 01:49:551037#endif // defined(OS_WIN)
1038
1039#endif // !defined(DISABLE_FILE_SUPPORT)
1040
1041TEST_F(URLRequestTest, InvalidUrlTest) {
1042 TestDelegate d;
1043 {
[email protected]f7022f32014-08-21 16:32:191044 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361045 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551046
[email protected]f7022f32014-08-21 16:32:191047 r->Start();
1048 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551049
1050 base::RunLoop().Run();
1051 EXPECT_TRUE(d.request_failed());
1052 }
1053}
1054
jochen0e3b3a62014-09-16 18:31:231055TEST_F(URLRequestTest, InvalidReferrerTest) {
1056 TestURLRequestContext context;
1057 TestNetworkDelegate network_delegate;
1058 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1059 context.set_network_delegate(&network_delegate);
1060 TestDelegate d;
davidben151423e2015-03-23 18:48:361061 scoped_ptr<URLRequest> req(
1062 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231063 req->SetReferrer("https://somewhere.com/");
1064
1065 req->Start();
1066 base::RunLoop().Run();
1067 EXPECT_TRUE(d.request_failed());
1068}
1069
[email protected]5ecf7cb282014-05-11 01:49:551070#if defined(OS_WIN)
1071TEST_F(URLRequestTest, ResolveShortcutTest) {
1072 base::FilePath app_path;
1073 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1074 app_path = app_path.AppendASCII("net");
1075 app_path = app_path.AppendASCII("data");
1076 app_path = app_path.AppendASCII("url_request_unittest");
1077 app_path = app_path.AppendASCII("with-headers.html");
1078
1079 std::wstring lnk_path = app_path.value() + L".lnk";
1080
1081 base::win::ScopedCOMInitializer com_initializer;
1082
1083 // Temporarily create a shortcut for test
1084 {
1085 base::win::ScopedComPtr<IShellLink> shell;
1086 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1087 CLSCTX_INPROC_SERVER)));
1088 base::win::ScopedComPtr<IPersistFile> persist;
1089 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1090 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1091 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1092 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1093 }
1094
1095 TestDelegate d;
1096 {
[email protected]f7022f32014-08-21 16:32:191097 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361098 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551099
[email protected]f7022f32014-08-21 16:32:191100 r->Start();
1101 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551102
1103 base::RunLoop().Run();
1104
1105 WIN32_FILE_ATTRIBUTE_DATA data;
1106 GetFileAttributesEx(app_path.value().c_str(),
1107 GetFileExInfoStandard, &data);
1108 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1109 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1110 FILE_ATTRIBUTE_NORMAL, NULL);
1111 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1112 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1113 DWORD read_size;
1114 BOOL result;
1115 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1116 &read_size, NULL);
1117 std::string content(buffer.get(), read_size);
1118 CloseHandle(file);
1119
[email protected]f7022f32014-08-21 16:32:191120 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551121 EXPECT_EQ(1, d.received_redirect_count());
1122 EXPECT_EQ(content, d.data_received());
1123 }
1124
1125 // Clean the shortcut
1126 DeleteFile(lnk_path.c_str());
1127}
1128#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441129
1130// Custom URLRequestJobs for use with interceptor tests
1131class RestartTestJob : public URLRequestTestJob {
1132 public:
1133 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1134 : URLRequestTestJob(request, network_delegate, true) {}
1135 protected:
dchengb03027d2014-10-21 12:00:201136 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441137 private:
dchengb03027d2014-10-21 12:00:201138 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441139};
1140
1141class CancelTestJob : public URLRequestTestJob {
1142 public:
1143 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1144 : URLRequestTestJob(request, network_delegate, true) {}
1145 protected:
dchengb03027d2014-10-21 12:00:201146 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441147 private:
dchengb03027d2014-10-21 12:00:201148 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441149};
1150
1151class CancelThenRestartTestJob : public URLRequestTestJob {
1152 public:
1153 explicit CancelThenRestartTestJob(URLRequest* request,
1154 NetworkDelegate* network_delegate)
1155 : URLRequestTestJob(request, network_delegate, true) {
1156 }
1157 protected:
dchengb03027d2014-10-21 12:00:201158 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441159 request_->Cancel();
1160 this->NotifyRestartRequired();
1161 }
1162 private:
dchengb03027d2014-10-21 12:00:201163 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441164};
1165
bengr1bf8e942014-11-07 01:36:501166// An Interceptor for use with interceptor tests.
1167class MockURLRequestInterceptor : public URLRequestInterceptor {
1168 public:
1169 // Static getters for canned response header and data strings.
1170 static std::string ok_data() {
1171 return URLRequestTestJob::test_data_1();
1172 }
1173
1174 static std::string ok_headers() {
1175 return URLRequestTestJob::test_headers();
1176 }
1177
1178 static std::string redirect_data() {
1179 return std::string();
1180 }
1181
1182 static std::string redirect_headers() {
1183 return URLRequestTestJob::test_redirect_headers();
1184 }
1185
1186 static std::string error_data() {
1187 return std::string("ohhh nooooo mr. bill!");
1188 }
1189
1190 static std::string error_headers() {
1191 return URLRequestTestJob::test_error_headers();
1192 }
1193
1194 MockURLRequestInterceptor()
1195 : intercept_main_request_(false), restart_main_request_(false),
1196 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1197 simulate_main_network_error_(false),
1198 intercept_redirect_(false), cancel_redirect_request_(false),
1199 intercept_final_response_(false), cancel_final_request_(false),
1200 use_url_request_http_job_(false),
1201 did_intercept_main_(false), did_restart_main_(false),
1202 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1203 did_simulate_error_main_(false),
1204 did_intercept_redirect_(false), did_cancel_redirect_(false),
1205 did_intercept_final_(false), did_cancel_final_(false) {
1206 }
1207
1208 ~MockURLRequestInterceptor() override {
1209 }
1210
1211 // URLRequestInterceptor implementation:
1212 URLRequestJob* MaybeInterceptRequest(
1213 URLRequest* request,
1214 NetworkDelegate* network_delegate) const override {
1215 if (restart_main_request_) {
1216 restart_main_request_ = false;
1217 did_restart_main_ = true;
1218 return new RestartTestJob(request, network_delegate);
1219 }
1220 if (cancel_main_request_) {
1221 cancel_main_request_ = false;
1222 did_cancel_main_ = true;
1223 return new CancelTestJob(request, network_delegate);
1224 }
1225 if (cancel_then_restart_main_request_) {
1226 cancel_then_restart_main_request_ = false;
1227 did_cancel_then_restart_main_ = true;
1228 return new CancelThenRestartTestJob(request, network_delegate);
1229 }
1230 if (simulate_main_network_error_) {
1231 simulate_main_network_error_ = false;
1232 did_simulate_error_main_ = true;
1233 if (use_url_request_http_job_) {
1234 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1235 }
1236 // This job will result in error since the requested URL is not one of the
1237 // URLs supported by these tests.
1238 return new URLRequestTestJob(request, network_delegate, true);
1239 }
1240 if (!intercept_main_request_)
1241 return nullptr;
1242 intercept_main_request_ = false;
1243 did_intercept_main_ = true;
1244 URLRequestTestJob* job = new URLRequestTestJob(request,
1245 network_delegate,
1246 main_headers_,
1247 main_data_,
1248 true);
1249 job->set_load_timing_info(main_request_load_timing_info_);
1250 return job;
1251 }
1252
1253 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1254 NetworkDelegate* network_delegate,
1255 const GURL& location) const override {
1256 if (cancel_redirect_request_) {
1257 cancel_redirect_request_ = false;
1258 did_cancel_redirect_ = true;
1259 return new CancelTestJob(request, network_delegate);
1260 }
1261 if (!intercept_redirect_)
1262 return nullptr;
1263 intercept_redirect_ = false;
1264 did_intercept_redirect_ = true;
1265 if (use_url_request_http_job_) {
1266 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1267 }
1268 return new URLRequestTestJob(request,
1269 network_delegate,
1270 redirect_headers_,
1271 redirect_data_,
1272 true);
1273 }
1274
1275 URLRequestJob* MaybeInterceptResponse(
1276 URLRequest* request,
1277 NetworkDelegate* network_delegate) const override {
1278 if (cancel_final_request_) {
1279 cancel_final_request_ = false;
1280 did_cancel_final_ = true;
1281 return new CancelTestJob(request, network_delegate);
1282 }
1283 if (!intercept_final_response_)
1284 return nullptr;
1285 intercept_final_response_ = false;
1286 did_intercept_final_ = true;
1287 if (use_url_request_http_job_) {
1288 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1289 }
1290 return new URLRequestTestJob(request,
1291 network_delegate,
1292 final_headers_,
1293 final_data_,
1294 true);
1295 }
1296
1297 void set_intercept_main_request(bool intercept_main_request) {
1298 intercept_main_request_ = intercept_main_request;
1299 }
1300
1301 void set_main_headers(const std::string& main_headers) {
1302 main_headers_ = main_headers;
1303 }
1304
1305 void set_main_data(const std::string& main_data) {
1306 main_data_ = main_data;
1307 }
1308
1309 void set_main_request_load_timing_info(
1310 const LoadTimingInfo& main_request_load_timing_info) {
1311 main_request_load_timing_info_ = main_request_load_timing_info;
1312 }
1313
1314 void set_restart_main_request(bool restart_main_request) {
1315 restart_main_request_ = restart_main_request;
1316 }
1317
1318 void set_cancel_main_request(bool cancel_main_request) {
1319 cancel_main_request_ = cancel_main_request;
1320 }
1321
1322 void set_cancel_then_restart_main_request(
1323 bool cancel_then_restart_main_request) {
1324 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1325 }
1326
1327 void set_simulate_main_network_error(bool simulate_main_network_error) {
1328 simulate_main_network_error_ = simulate_main_network_error;
1329 }
1330
1331 void set_intercept_redirect(bool intercept_redirect) {
1332 intercept_redirect_ = intercept_redirect;
1333 }
1334
1335 void set_redirect_headers(const std::string& redirect_headers) {
1336 redirect_headers_ = redirect_headers;
1337 }
1338
1339 void set_redirect_data(const std::string& redirect_data) {
1340 redirect_data_ = redirect_data;
1341 }
1342
1343 void set_cancel_redirect_request(bool cancel_redirect_request) {
1344 cancel_redirect_request_ = cancel_redirect_request;
1345 }
1346
1347 void set_intercept_final_response(bool intercept_final_response) {
1348 intercept_final_response_ = intercept_final_response;
1349 }
1350
1351 void set_final_headers(const std::string& final_headers) {
1352 final_headers_ = final_headers;
1353 }
1354
1355 void set_final_data(const std::string& final_data) {
1356 final_data_ = final_data;
1357 }
1358
1359 void set_cancel_final_request(bool cancel_final_request) {
1360 cancel_final_request_ = cancel_final_request;
1361 }
1362
1363 void set_use_url_request_http_job(bool use_url_request_http_job) {
1364 use_url_request_http_job_ = use_url_request_http_job;
1365 }
1366
1367 bool did_intercept_main() const {
1368 return did_intercept_main_;
1369 }
1370
1371 bool did_restart_main() const {
1372 return did_restart_main_;
1373 }
1374
1375 bool did_cancel_main() const {
1376 return did_cancel_main_;
1377 }
1378
1379 bool did_cancel_then_restart_main() const {
1380 return did_cancel_then_restart_main_;
1381 }
1382
1383 bool did_simulate_error_main() const {
1384 return did_simulate_error_main_;
1385 }
1386
1387 bool did_intercept_redirect() const {
1388 return did_intercept_redirect_;
1389 }
1390
1391 bool did_cancel_redirect() const {
1392 return did_cancel_redirect_;
1393 }
1394
1395 bool did_intercept_final() const {
1396 return did_intercept_final_;
1397 }
1398
1399 bool did_cancel_final() const {
1400 return did_cancel_final_;
1401 }
1402
1403 private:
1404 // Indicate whether to intercept the main request, and if so specify the
1405 // response to return and the LoadTimingInfo to use.
1406 mutable bool intercept_main_request_;
1407 mutable std::string main_headers_;
1408 mutable std::string main_data_;
1409 mutable LoadTimingInfo main_request_load_timing_info_;
1410
1411 // These indicate actions that can be taken within MaybeInterceptRequest.
1412 mutable bool restart_main_request_;
1413 mutable bool cancel_main_request_;
1414 mutable bool cancel_then_restart_main_request_;
1415 mutable bool simulate_main_network_error_;
1416
1417 // Indicate whether to intercept redirects, and if so specify the response to
1418 // return.
1419 mutable bool intercept_redirect_;
1420 mutable std::string redirect_headers_;
1421 mutable std::string redirect_data_;
1422
1423 // Cancel the request within MaybeInterceptRedirect.
1424 mutable bool cancel_redirect_request_;
1425
1426 // Indicate whether to intercept the final response, and if so specify the
1427 // response to return.
1428 mutable bool intercept_final_response_;
1429 mutable std::string final_headers_;
1430 mutable std::string final_data_;
1431
1432 // Cancel the final request within MaybeInterceptResponse.
1433 mutable bool cancel_final_request_;
1434
1435 // Instruct the interceptor to use a real URLRequestHTTPJob.
1436 mutable bool use_url_request_http_job_;
1437
1438 // These indicate if the interceptor did something or not.
1439 mutable bool did_intercept_main_;
1440 mutable bool did_restart_main_;
1441 mutable bool did_cancel_main_;
1442 mutable bool did_cancel_then_restart_main_;
1443 mutable bool did_simulate_error_main_;
1444 mutable bool did_intercept_redirect_;
1445 mutable bool did_cancel_redirect_;
1446 mutable bool did_intercept_final_;
1447 mutable bool did_cancel_final_;
1448};
1449
1450// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1451class URLRequestInterceptorTest : public URLRequestTest {
1452 public:
1453 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1454 }
1455
1456 ~URLRequestInterceptorTest() override {
1457 // URLRequestJobs may post clean-up tasks on destruction.
1458 base::RunLoop().RunUntilIdle();
1459 }
1460
1461 void SetUpFactory() override {
1462 interceptor_ = new MockURLRequestInterceptor();
1463 job_factory_.reset(new URLRequestInterceptingJobFactory(
1464 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1465 }
1466
1467 MockURLRequestInterceptor* interceptor() const {
1468 return interceptor_;
1469 }
1470
1471 private:
1472 MockURLRequestInterceptor* interceptor_;
1473};
1474
1475TEST_F(URLRequestInterceptorTest, Intercept) {
1476 // Intercept the main request and respond with a simple response.
1477 interceptor()->set_intercept_main_request(true);
1478 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1479 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591480 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501481 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361482 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501483 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1484 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1485 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1486 req->SetUserData(nullptr, user_data0);
1487 req->SetUserData(&user_data1, user_data1);
1488 req->SetUserData(&user_data2, user_data2);
1489 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191490 req->Start();
[email protected]255620da2013-08-19 13:14:291491 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591492
bengr1bf8e942014-11-07 01:36:501493 // Make sure we can retrieve our specific user data.
1494 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1495 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1496 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591497
bengr1bf8e942014-11-07 01:36:501498 // Check that we got one good response.
1499 EXPECT_TRUE(req->status().is_success());
1500 EXPECT_EQ(200, req->response_headers()->response_code());
1501 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1502 EXPECT_EQ(1, d.response_started_count());
1503 EXPECT_EQ(0, d.received_redirect_count());
1504}
[email protected]2bba3252013-04-08 19:50:591505
bengr1bf8e942014-11-07 01:36:501506TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1507 // Intercept the main request and respond with a redirect.
1508 interceptor()->set_intercept_main_request(true);
1509 interceptor()->set_main_headers(
1510 MockURLRequestInterceptor::redirect_headers());
1511 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1512
1513 // Intercept that redirect and respond with a final OK response.
1514 interceptor()->set_intercept_redirect(true);
1515 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1516 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1517
1518 TestDelegate d;
1519 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361520 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501521 req->set_method("GET");
1522 req->Start();
1523 base::RunLoop().Run();
1524
1525 // Check that the interceptor got called as expected.
1526 EXPECT_TRUE(interceptor()->did_intercept_main());
1527 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1528
1529 // Check that we got one good response.
1530 EXPECT_TRUE(req->status().is_success());
1531 if (req->status().is_success())
1532 EXPECT_EQ(200, req->response_headers()->response_code());
1533
1534 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1535 EXPECT_EQ(1, d.response_started_count());
1536 EXPECT_EQ(0, d.received_redirect_count());
1537}
1538
1539TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1540 // Intercept the main request to generate a server error response.
1541 interceptor()->set_intercept_main_request(true);
1542 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1543 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1544
1545 // Intercept that error and respond with an OK response.
1546 interceptor()->set_intercept_final_response(true);
1547 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1548 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1549
1550 TestDelegate d;
1551 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361552 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501553 req->set_method("GET");
1554 req->Start();
1555 base::RunLoop().Run();
1556
1557 // Check that the interceptor got called as expected.
1558 EXPECT_TRUE(interceptor()->did_intercept_main());
1559 EXPECT_TRUE(interceptor()->did_intercept_final());
1560
1561 // Check that we got one good response.
1562 EXPECT_TRUE(req->status().is_success());
1563 EXPECT_EQ(200, req->response_headers()->response_code());
1564 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1565 EXPECT_EQ(1, d.response_started_count());
1566 EXPECT_EQ(0, d.received_redirect_count());
1567}
1568
1569TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1570 // Intercept the main request to simulate a network error.
1571 interceptor()->set_simulate_main_network_error(true);
1572
1573 // Intercept that error and respond with an OK response.
1574 interceptor()->set_intercept_final_response(true);
1575 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1576 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1577
1578 TestDelegate d;
1579 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361580 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501581 req->set_method("GET");
1582 req->Start();
1583 base::RunLoop().Run();
1584
1585 // Check that the interceptor got called as expected.
1586 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1587 EXPECT_TRUE(interceptor()->did_intercept_final());
1588
1589 // Check that we received one good response.
1590 EXPECT_TRUE(req->status().is_success());
1591 EXPECT_EQ(200, req->response_headers()->response_code());
1592 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1593 EXPECT_EQ(1, d.response_started_count());
1594 EXPECT_EQ(0, d.received_redirect_count());
1595}
1596
1597TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1598 // Restart the main request.
1599 interceptor()->set_restart_main_request(true);
1600
1601 // then intercept the new main request and respond with an OK response
1602 interceptor()->set_intercept_main_request(true);
1603 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1604 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1605
1606 TestDelegate d;
1607 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361608 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501609 req->set_method("GET");
1610 req->Start();
1611 base::RunLoop().Run();
1612
1613 // Check that the interceptor got called as expected.
1614 EXPECT_TRUE(interceptor()->did_restart_main());
1615 EXPECT_TRUE(interceptor()->did_intercept_main());
1616
1617 // Check that we received one good response.
1618 EXPECT_TRUE(req->status().is_success());
1619 if (req->status().is_success())
1620 EXPECT_EQ(200, req->response_headers()->response_code());
1621
1622 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1623 EXPECT_EQ(1, d.response_started_count());
1624 EXPECT_EQ(0, d.received_redirect_count());
1625}
1626
1627TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1628 // Intercept the main request and cancel from within the restarted job.
1629 interceptor()->set_cancel_main_request(true);
1630
1631 // Set up to intercept the final response and override it with an OK response.
1632 interceptor()->set_intercept_final_response(true);
1633 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1634 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1635
1636 TestDelegate d;
1637 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361638 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501639 req->set_method("GET");
1640 req->Start();
1641 base::RunLoop().Run();
1642
1643 // Check that the interceptor got called as expected.
1644 EXPECT_TRUE(interceptor()->did_cancel_main());
1645 EXPECT_FALSE(interceptor()->did_intercept_final());
1646
1647 // Check that we see a canceled request.
1648 EXPECT_FALSE(req->status().is_success());
1649 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1650}
1651
1652TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1653 // Intercept the main request and respond with a redirect.
1654 interceptor()->set_intercept_main_request(true);
1655 interceptor()->set_main_headers(
1656 MockURLRequestInterceptor::redirect_headers());
1657 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1658
1659 // Intercept the redirect and cancel from within that job.
1660 interceptor()->set_cancel_redirect_request(true);
1661
1662 // Set up to intercept the final response and override it with an OK response.
1663 interceptor()->set_intercept_final_response(true);
1664 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1665 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1666
1667 TestDelegate d;
1668 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361669 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501670 req->set_method("GET");
1671 req->Start();
1672 base::RunLoop().Run();
1673
1674 // Check that the interceptor got called as expected.
1675 EXPECT_TRUE(interceptor()->did_intercept_main());
1676 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1677 EXPECT_FALSE(interceptor()->did_intercept_final());
1678
1679 // Check that we see a canceled request.
1680 EXPECT_FALSE(req->status().is_success());
1681 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1682}
1683
1684TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1685 // Intercept the main request to simulate a network error.
1686 interceptor()->set_simulate_main_network_error(true);
1687
1688 // Set up to intercept final the response and cancel from within that job.
1689 interceptor()->set_cancel_final_request(true);
1690
1691 TestDelegate d;
1692 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361693 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501694 req->set_method("GET");
1695 req->Start();
1696 base::RunLoop().Run();
1697
1698 // Check that the interceptor got called as expected.
1699 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1700 EXPECT_TRUE(interceptor()->did_cancel_final());
1701
1702 // Check that we see a canceled request.
1703 EXPECT_FALSE(req->status().is_success());
1704 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1705}
1706
1707TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1708 // Intercept the main request and cancel then restart from within that job.
1709 interceptor()->set_cancel_then_restart_main_request(true);
1710
1711 // Set up to intercept the final response and override it with an OK response.
1712 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501713 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1714 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501715
1716 TestDelegate d;
1717 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361718 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501719 req->set_method("GET");
1720 req->Start();
1721 base::RunLoop().Run();
1722
1723 // Check that the interceptor got called as expected.
1724 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1725 EXPECT_FALSE(interceptor()->did_intercept_final());
1726
1727 // Check that we see a canceled request.
1728 EXPECT_FALSE(req->status().is_success());
1729 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591730}
1731
1732// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1733// reused. |connect_time_flags| is used to indicate if there should be dns
1734// or SSL times, and |used_proxy| is used for proxy times.
1735LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1736 int connect_time_flags,
1737 bool used_proxy) {
1738 LoadTimingInfo load_timing;
1739 load_timing.socket_log_id = 1;
1740
1741 if (used_proxy) {
1742 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1743 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1744 }
1745
1746 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1747 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1748 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1749 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1750 }
1751 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1752 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1753 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1754 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1755 }
1756 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1757
1758 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1759 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1760 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1761 return load_timing;
1762}
1763
1764// Same as above, but in the case of a reused socket.
1765LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1766 bool used_proxy) {
1767 LoadTimingInfo load_timing;
1768 load_timing.socket_log_id = 1;
1769 load_timing.socket_reused = true;
1770
1771 if (used_proxy) {
1772 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1773 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1774 }
1775
1776 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1777 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1778 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1779 return load_timing;
1780}
1781
bengr1bf8e942014-11-07 01:36:501782LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1783 const LoadTimingInfo& job_load_timing,
1784 const URLRequestContext& context,
1785 MockURLRequestInterceptor* interceptor) {
1786 interceptor->set_intercept_main_request(true);
1787 interceptor->set_main_request_load_timing_info(job_load_timing);
1788 TestDelegate d;
1789 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361790 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501791 req->Start();
1792 base::RunLoop().Run();
1793
1794 LoadTimingInfo resulting_load_timing;
1795 req->GetLoadTimingInfo(&resulting_load_timing);
1796
1797 // None of these should be modified by the URLRequest.
1798 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1799 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1800 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1801 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1802 EXPECT_EQ(job_load_timing.receive_headers_end,
1803 resulting_load_timing.receive_headers_end);
1804
1805 return resulting_load_timing;
1806}
1807
[email protected]2bba3252013-04-08 19:50:591808// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501809TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591810 base::TimeTicks now = base::TimeTicks::Now();
1811 LoadTimingInfo job_load_timing =
1812 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1813
[email protected]2ca01e52013-10-31 22:05:191814 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501815 RunURLRequestInterceptorLoadTimingTest(
1816 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591817
1818 // Nothing should have been changed by the URLRequest.
1819 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1820 load_timing_result.proxy_resolve_start);
1821 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1822 load_timing_result.proxy_resolve_end);
1823 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1824 load_timing_result.connect_timing.dns_start);
1825 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1826 load_timing_result.connect_timing.dns_end);
1827 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1828 load_timing_result.connect_timing.connect_start);
1829 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1830 load_timing_result.connect_timing.connect_end);
1831 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1832 load_timing_result.connect_timing.ssl_start);
1833 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1834 load_timing_result.connect_timing.ssl_end);
1835
1836 // Redundant sanity check.
1837 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1838}
1839
1840// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501841TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591842 base::TimeTicks now = base::TimeTicks::Now();
1843 LoadTimingInfo job_load_timing =
1844 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1845
[email protected]2ca01e52013-10-31 22:05:191846 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501847 RunURLRequestInterceptorLoadTimingTest(
1848 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591849
1850 // Nothing should have been changed by the URLRequest.
1851 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1852 load_timing_result.proxy_resolve_start);
1853 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1854 load_timing_result.proxy_resolve_end);
1855 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1856 load_timing_result.connect_timing.dns_start);
1857 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1858 load_timing_result.connect_timing.dns_end);
1859 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1860 load_timing_result.connect_timing.connect_start);
1861 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1862 load_timing_result.connect_timing.connect_end);
1863 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1864 load_timing_result.connect_timing.ssl_start);
1865 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1866 load_timing_result.connect_timing.ssl_end);
1867
1868 // Redundant sanity check.
1869 TestLoadTimingNotReusedWithProxy(load_timing_result,
1870 CONNECT_TIMING_HAS_SSL_TIMES);
1871}
1872
1873// Make sure that URLRequest correctly adjusts proxy times when they're before
1874// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101875// the case of reusing a SPDY session. The connected socket is not considered
1876// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591877//
1878// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501879TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591880 base::TimeTicks now = base::TimeTicks::Now();
1881 LoadTimingInfo job_load_timing =
1882 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1883 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1884 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1885 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1886 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1887 job_load_timing.connect_timing.connect_start =
1888 now - base::TimeDelta::FromDays(2);
1889 job_load_timing.connect_timing.connect_end =
1890 now - base::TimeDelta::FromDays(1);
1891
[email protected]2ca01e52013-10-31 22:05:191892 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501893 RunURLRequestInterceptorLoadTimingTest(
1894 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591895
1896 // Proxy times, connect times, and DNS times should all be replaced with
1897 // request_start.
1898 EXPECT_EQ(load_timing_result.request_start,
1899 load_timing_result.proxy_resolve_start);
1900 EXPECT_EQ(load_timing_result.request_start,
1901 load_timing_result.proxy_resolve_end);
1902 EXPECT_EQ(load_timing_result.request_start,
1903 load_timing_result.connect_timing.dns_start);
1904 EXPECT_EQ(load_timing_result.request_start,
1905 load_timing_result.connect_timing.dns_end);
1906 EXPECT_EQ(load_timing_result.request_start,
1907 load_timing_result.connect_timing.connect_start);
1908 EXPECT_EQ(load_timing_result.request_start,
1909 load_timing_result.connect_timing.connect_end);
1910
1911 // Other times should have been left null.
1912 TestLoadTimingNotReusedWithProxy(load_timing_result,
1913 CONNECT_TIMING_HAS_DNS_TIMES);
1914}
1915
1916// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:501917TEST_F(URLRequestInterceptorTest,
1918 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:591919 base::TimeTicks now = base::TimeTicks::Now();
1920 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1921 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1922 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1923
[email protected]2ca01e52013-10-31 22:05:191924 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501925 RunURLRequestInterceptorLoadTimingTest(
1926 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591927
1928 // Proxy times and connect times should all be replaced with request_start.
1929 EXPECT_EQ(load_timing_result.request_start,
1930 load_timing_result.proxy_resolve_start);
1931 EXPECT_EQ(load_timing_result.request_start,
1932 load_timing_result.proxy_resolve_end);
1933
1934 // Other times should have been left null.
1935 TestLoadTimingReusedWithProxy(load_timing_result);
1936}
1937
1938// Make sure that URLRequest correctly adjusts connect times when they're before
1939// |request_start|, due to reusing a connected socket. The connected socket is
1940// not considered reused in this test (May be a preconnect).
1941//
1942// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501943TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:591944 base::TimeTicks now = base::TimeTicks::Now();
1945 LoadTimingInfo job_load_timing =
1946 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1947 job_load_timing.connect_timing.connect_start =
1948 now - base::TimeDelta::FromDays(1);
1949 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1950 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1951 job_load_timing.connect_timing.connect_end =
1952 now - base::TimeDelta::FromDays(4);
1953
[email protected]2ca01e52013-10-31 22:05:191954 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501955 RunURLRequestInterceptorLoadTimingTest(
1956 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591957
1958 // Connect times, and SSL times should be replaced with request_start.
1959 EXPECT_EQ(load_timing_result.request_start,
1960 load_timing_result.connect_timing.connect_start);
1961 EXPECT_EQ(load_timing_result.request_start,
1962 load_timing_result.connect_timing.ssl_start);
1963 EXPECT_EQ(load_timing_result.request_start,
1964 load_timing_result.connect_timing.ssl_end);
1965 EXPECT_EQ(load_timing_result.request_start,
1966 load_timing_result.connect_timing.connect_end);
1967
1968 // Other times should have been left null.
1969 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1970}
1971
1972// Make sure that URLRequest correctly adjusts connect times when they're before
1973// |request_start|, due to reusing a connected socket in the case that there
1974// are also proxy times. The connected socket is not considered reused in this
1975// test (May be a preconnect).
1976//
1977// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:501978TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:591979 base::TimeTicks now = base::TimeTicks::Now();
1980 LoadTimingInfo job_load_timing =
1981 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1982 job_load_timing.connect_timing.connect_start =
1983 now - base::TimeDelta::FromDays(1);
1984 job_load_timing.connect_timing.connect_end =
1985 now - base::TimeDelta::FromDays(2);
1986
[email protected]2ca01e52013-10-31 22:05:191987 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501988 RunURLRequestInterceptorLoadTimingTest(
1989 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591990
1991 // Connect times should be replaced with proxy_resolve_end.
1992 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1993 load_timing_result.connect_timing.connect_start);
1994 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1995 load_timing_result.connect_timing.connect_end);
1996
1997 // Other times should have been left null.
1998 TestLoadTimingNotReusedWithProxy(load_timing_result,
1999 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2000}
2001
[email protected]316c1e5e2012-09-12 15:17:442002// Check that two different URL requests have different identifiers.
2003TEST_F(URLRequestTest, Identifiers) {
2004 TestDelegate d;
2005 TestURLRequestContext context;
davidben151423e2015-03-23 18:48:362006 scoped_ptr<URLRequest> req(
2007 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2008 scoped_ptr<URLRequest> other_req(
2009 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442010
mmenke19378d22014-09-09 04:12:592011 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442012}
2013
2014// Check that a failure to connect to the proxy is reported to the network
2015// delegate.
2016TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2017 MockHostResolver host_resolver;
2018 host_resolver.rules()->AddSimulatedFailure("*");
2019
[email protected]ceefd7fd2012-11-29 00:36:242020 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442021 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2022
2023 TestDelegate d;
davidben151423e2015-03-23 18:48:362024 scoped_ptr<URLRequest> req(
2025 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192026 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442027
[email protected]f7022f32014-08-21 16:32:192028 req->Start();
[email protected]255620da2013-08-19 13:14:292029 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442030
2031 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192032 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152033 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192034 EXPECT_TRUE(req->proxy_server().IsEmpty());
2035 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2036 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442037
2038 EXPECT_EQ(1, network_delegate.error_count());
2039 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2040 EXPECT_EQ(1, network_delegate.completed_requests());
2041}
2042
[email protected]cba24642014-08-15 20:49:592043// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442044// content is empty.
2045TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2046 TestDelegate d;
davidben151423e2015-03-23 18:48:362047 scoped_ptr<URLRequest> req(
2048 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192049 req->Start();
[email protected]255620da2013-08-19 13:14:292050 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442051 EXPECT_EQ("", d.data_received());
2052 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2053}
2054
[email protected]5033ab82013-03-22 20:17:462055// Make sure that SetPriority actually sets the URLRequest's priority
2056// correctly, both before and after start.
2057TEST_F(URLRequestTest, SetPriorityBasic) {
2058 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192059 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362060 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192061 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462062
[email protected]f7022f32014-08-21 16:32:192063 req->SetPriority(LOW);
2064 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462065
[email protected]f7022f32014-08-21 16:32:192066 req->Start();
2067 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462068
[email protected]f7022f32014-08-21 16:32:192069 req->SetPriority(MEDIUM);
2070 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462071}
2072
2073// Make sure that URLRequest calls SetPriority on a job before calling
2074// Start on it.
2075TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2076 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192077 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362078 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192079 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462080
2081 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192082 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502083 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462084 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2085
[email protected]f7022f32014-08-21 16:32:192086 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462087
[email protected]f7022f32014-08-21 16:32:192088 req->Start();
[email protected]5033ab82013-03-22 20:17:462089 EXPECT_EQ(LOW, job->priority());
2090}
2091
2092// Make sure that URLRequest passes on its priority updates to its
2093// job.
2094TEST_F(URLRequestTest, SetJobPriority) {
2095 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192096 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362097 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462098
2099 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192100 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502101 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462102
[email protected]f7022f32014-08-21 16:32:192103 req->SetPriority(LOW);
2104 req->Start();
[email protected]5033ab82013-03-22 20:17:462105 EXPECT_EQ(LOW, job->priority());
2106
[email protected]f7022f32014-08-21 16:32:192107 req->SetPriority(MEDIUM);
2108 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462109 EXPECT_EQ(MEDIUM, job->priority());
2110}
2111
[email protected]bb1c4662013-11-14 00:00:072112// Setting the IGNORE_LIMITS load flag should be okay if the priority
2113// is MAXIMUM_PRIORITY.
2114TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2115 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192116 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362117 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192118 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072119
2120 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192121 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]bb1c4662013-11-14 00:00:072122 AddTestInterceptor()->set_main_intercept_job(job.get());
2123
[email protected]f7022f32014-08-21 16:32:192124 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2125 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072126
[email protected]f7022f32014-08-21 16:32:192127 req->SetPriority(MAXIMUM_PRIORITY);
2128 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072129
[email protected]f7022f32014-08-21 16:32:192130 req->Start();
2131 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072132 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2133}
2134
[email protected]ce7d0cbc2013-05-03 18:57:222135// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:442136#if !defined(OS_IOS)
nick5d570de92015-05-04 20:16:162137namespace {
2138
2139// Less verbose way of running a simple testserver for the tests below.
[email protected]ce7d0cbc2013-05-03 18:57:222140class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442141 public:
[email protected]6cdfd7f2013-02-08 20:40:152142 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:222143 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162144 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222145 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:442146 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:222147 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162148 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222149 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:442150};
2151
nick5d570de92015-05-04 20:16:162152} // namespace
2153
[email protected]f2f31b32013-01-16 23:24:092154TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442155 LocalHttpTestServer test_server;
2156 ASSERT_TRUE(test_server.Start());
2157
2158 TestURLRequestContext context;
2159 scoped_refptr<DelayedCookieMonster> delayed_cm =
2160 new DelayedCookieMonster();
2161 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502162 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442163
2164 // Set up a cookie.
2165 {
2166 TestNetworkDelegate network_delegate;
2167 context.set_network_delegate(&network_delegate);
2168 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192169 scoped_ptr<URLRequest> req(context.CreateRequest(
2170 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362171 &d));
[email protected]f7022f32014-08-21 16:32:192172 req->Start();
[email protected]255620da2013-08-19 13:14:292173 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442174 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2175 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2176 EXPECT_EQ(1, network_delegate.set_cookie_count());
2177 }
2178
2179 // Verify that the cookie is set.
2180 {
2181 TestNetworkDelegate network_delegate;
2182 context.set_network_delegate(&network_delegate);
2183 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192184 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:362185 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192186 req->Start();
[email protected]255620da2013-08-19 13:14:292187 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442188
2189 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2190 != std::string::npos);
2191 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2192 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2193 }
2194}
2195
[email protected]f2f31b32013-01-16 23:24:092196TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442197 LocalHttpTestServer test_server;
2198 ASSERT_TRUE(test_server.Start());
2199
2200 // Set up a cookie.
2201 {
2202 TestNetworkDelegate network_delegate;
2203 default_context_.set_network_delegate(&network_delegate);
2204 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192205 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2206 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362207 &d));
[email protected]f7022f32014-08-21 16:32:192208 req->Start();
[email protected]255620da2013-08-19 13:14:292209 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442210 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2211 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2212 }
2213
2214 // Verify that the cookie is set.
2215 {
2216 TestNetworkDelegate network_delegate;
2217 default_context_.set_network_delegate(&network_delegate);
2218 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192219 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362220 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192221 req->Start();
[email protected]255620da2013-08-19 13:14:292222 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442223
2224 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2225 != std::string::npos);
2226 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2227 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2228 }
2229
2230 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2231 {
2232 TestNetworkDelegate network_delegate;
2233 default_context_.set_network_delegate(&network_delegate);
2234 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192235 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362236 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192237 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2238 req->Start();
[email protected]255620da2013-08-19 13:14:292239 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442240
2241 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2242 == std::string::npos);
2243
2244 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2245 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2246 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2247 }
2248}
2249
2250TEST_F(URLRequestTest, DoNotSaveCookies) {
2251 LocalHttpTestServer test_server;
2252 ASSERT_TRUE(test_server.Start());
2253
2254 // Set up a cookie.
2255 {
2256 TestNetworkDelegate network_delegate;
2257 default_context_.set_network_delegate(&network_delegate);
2258 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192259 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2260 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362261 &d));
[email protected]f7022f32014-08-21 16:32:192262 req->Start();
[email protected]255620da2013-08-19 13:14:292263 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442264
2265 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2266 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2267 EXPECT_EQ(1, network_delegate.set_cookie_count());
2268 }
2269
2270 // Try to set-up another cookie and update the previous cookie.
2271 {
2272 TestNetworkDelegate network_delegate;
2273 default_context_.set_network_delegate(&network_delegate);
2274 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192275 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442276 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362277 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192278 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2279 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442280
[email protected]255620da2013-08-19 13:14:292281 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442282
2283 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2284 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2285 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2286 EXPECT_EQ(0, network_delegate.set_cookie_count());
2287 }
2288
2289 // Verify the cookies weren't saved or updated.
2290 {
2291 TestNetworkDelegate network_delegate;
2292 default_context_.set_network_delegate(&network_delegate);
2293 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192294 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362295 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192296 req->Start();
[email protected]255620da2013-08-19 13:14:292297 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442298
2299 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2300 == std::string::npos);
2301 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2302 != std::string::npos);
2303
2304 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2305 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2306 EXPECT_EQ(0, network_delegate.set_cookie_count());
2307 }
2308}
2309
2310TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2311 LocalHttpTestServer test_server;
2312 ASSERT_TRUE(test_server.Start());
2313
2314 // Set up a cookie.
2315 {
2316 TestNetworkDelegate network_delegate;
2317 default_context_.set_network_delegate(&network_delegate);
2318 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192319 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2320 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362321 &d));
[email protected]f7022f32014-08-21 16:32:192322 req->Start();
[email protected]255620da2013-08-19 13:14:292323 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442324
2325 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2326 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2327 }
2328
2329 // Verify that the cookie is set.
2330 {
2331 TestNetworkDelegate network_delegate;
2332 default_context_.set_network_delegate(&network_delegate);
2333 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192334 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362335 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192336 req->Start();
[email protected]255620da2013-08-19 13:14:292337 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442338
2339 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2340 != std::string::npos);
2341
2342 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2343 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2344 }
2345
2346 // Verify that the cookie isn't sent.
2347 {
2348 TestNetworkDelegate network_delegate;
2349 default_context_.set_network_delegate(&network_delegate);
2350 TestDelegate d;
2351 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192352 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362353 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192354 req->Start();
[email protected]255620da2013-08-19 13:14:292355 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442356
2357 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2358 == std::string::npos);
2359
[email protected]22e045f2013-09-20 03:54:032360 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442361 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2362 }
2363}
2364
2365TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2366 LocalHttpTestServer test_server;
2367 ASSERT_TRUE(test_server.Start());
2368
2369 // Set up a cookie.
2370 {
2371 TestNetworkDelegate network_delegate;
2372 default_context_.set_network_delegate(&network_delegate);
2373 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192374 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2375 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362376 &d));
[email protected]f7022f32014-08-21 16:32:192377 req->Start();
[email protected]255620da2013-08-19 13:14:292378 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442379
2380 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2381 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2382 }
2383
2384 // Try to set-up another cookie and update the previous cookie.
2385 {
2386 TestNetworkDelegate network_delegate;
2387 default_context_.set_network_delegate(&network_delegate);
2388 TestDelegate d;
2389 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192390 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442391 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362392 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192393 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442394
[email protected]255620da2013-08-19 13:14:292395 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442396
2397 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2398 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2399 }
2400
2401 // Verify the cookies weren't saved or updated.
2402 {
2403 TestNetworkDelegate network_delegate;
2404 default_context_.set_network_delegate(&network_delegate);
2405 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192406 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362407 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192408 req->Start();
[email protected]255620da2013-08-19 13:14:292409 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442410
2411 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2412 == std::string::npos);
2413 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2414 != std::string::npos);
2415
2416 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2417 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2418 }
2419}
2420
2421TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2422 LocalHttpTestServer test_server;
2423 ASSERT_TRUE(test_server.Start());
2424
2425 // Set up an empty cookie.
2426 {
2427 TestNetworkDelegate network_delegate;
2428 default_context_.set_network_delegate(&network_delegate);
2429 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192430 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362431 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192432 req->Start();
[email protected]255620da2013-08-19 13:14:292433 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442434
2435 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2436 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2437 EXPECT_EQ(0, network_delegate.set_cookie_count());
2438 }
2439}
2440
2441TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2442 LocalHttpTestServer test_server;
2443 ASSERT_TRUE(test_server.Start());
2444
2445 // Set up a cookie.
2446 {
2447 TestNetworkDelegate network_delegate;
2448 default_context_.set_network_delegate(&network_delegate);
2449 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192450 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2451 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362452 &d));
[email protected]f7022f32014-08-21 16:32:192453 req->Start();
[email protected]255620da2013-08-19 13:14:292454 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442455
2456 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2457 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2458 }
2459
2460 // Verify that the cookie is set.
2461 {
2462 TestNetworkDelegate network_delegate;
2463 default_context_.set_network_delegate(&network_delegate);
2464 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192465 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362466 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192467 req->Start();
[email protected]255620da2013-08-19 13:14:292468 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442469
2470 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2471 != std::string::npos);
2472
2473 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2474 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2475 }
2476
2477 // Verify that the cookie isn't sent.
2478 {
2479 TestNetworkDelegate network_delegate;
2480 default_context_.set_network_delegate(&network_delegate);
2481 TestDelegate d;
2482 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192483 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362484 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192485 req->Start();
[email protected]255620da2013-08-19 13:14:292486 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442487
2488 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2489 == std::string::npos);
2490
[email protected]22e045f2013-09-20 03:54:032491 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442492 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2493 }
2494}
2495
2496TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2497 LocalHttpTestServer test_server;
2498 ASSERT_TRUE(test_server.Start());
2499
2500 // Set up a cookie.
2501 {
2502 TestNetworkDelegate network_delegate;
2503 default_context_.set_network_delegate(&network_delegate);
2504 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192505 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2506 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362507 &d));
[email protected]f7022f32014-08-21 16:32:192508 req->Start();
[email protected]255620da2013-08-19 13:14:292509 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442510
2511 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2512 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2513 }
2514
2515 // Try to set-up another cookie and update the previous cookie.
2516 {
2517 TestNetworkDelegate network_delegate;
2518 default_context_.set_network_delegate(&network_delegate);
2519 TestDelegate d;
2520 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192521 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442522 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362523 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192524 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442525
[email protected]255620da2013-08-19 13:14:292526 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442527
2528 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2529 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2530 }
2531
2532 // Verify the cookies weren't saved or updated.
2533 {
2534 TestNetworkDelegate network_delegate;
2535 default_context_.set_network_delegate(&network_delegate);
2536 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192537 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362538 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192539 req->Start();
[email protected]255620da2013-08-19 13:14:292540 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442541
2542 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2543 == std::string::npos);
2544 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2545 != std::string::npos);
2546
2547 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2548 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2549 }
2550}
2551
mkwst3f3daac2015-02-26 20:15:262552TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2553 LocalHttpTestServer test_server;
2554 ASSERT_TRUE(test_server.Start());
2555
2556 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2557 // LocalHttpTestServer points).
2558 {
2559 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152560 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262561 default_context_.set_network_delegate(&network_delegate);
2562
2563 TestDelegate d;
2564 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2565 test_server.GetURL(
2566 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
davidben151423e2015-03-23 18:48:362567 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262568 req->Start();
2569 base::RunLoop().Run();
2570 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2571 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2572 EXPECT_EQ(1, network_delegate.set_cookie_count());
2573 }
2574
2575 // Verify that the cookie is sent for first-party requests.
2576 {
2577 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152578 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262579 default_context_.set_network_delegate(&network_delegate);
2580 TestDelegate d;
2581 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362582 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472583 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst3f3daac2015-02-26 20:15:262584 req->Start();
2585 base::RunLoop().Run();
2586
2587 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2588 std::string::npos);
2589 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2590 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2591 }
2592
2593 // Verify that the cookie is not-sent for non-first-party requests.
2594 {
2595 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152596 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262597 default_context_.set_network_delegate(&network_delegate);
2598 TestDelegate d;
2599 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362600 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262601 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2602 req->Start();
2603 base::RunLoop().Run();
2604
2605 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2606 std::string::npos);
2607 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2608 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2609 }
2610}
2611
mkwst0513c9d2015-04-01 05:53:152612TEST_F(URLRequestTest, FirstPartyOnlyCookiesDisabled) {
2613 LocalHttpTestServer test_server;
2614 ASSERT_TRUE(test_server.Start());
2615
2616 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2617 // LocalHttpTestServer points).
2618 {
2619 TestNetworkDelegate network_delegate;
2620 network_delegate.set_first_party_only_cookies_enabled(false);
2621 default_context_.set_network_delegate(&network_delegate);
2622
2623 TestDelegate d;
2624 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2625 test_server.GetURL(
2626 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
2627 DEFAULT_PRIORITY, &d));
2628 req->Start();
2629 base::RunLoop().Run();
2630 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2631 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2632 EXPECT_EQ(1, network_delegate.set_cookie_count());
2633 }
2634
2635 // Verify that the cookie is sent for first-party requests.
2636 {
2637 TestNetworkDelegate network_delegate;
2638 network_delegate.set_first_party_only_cookies_enabled(false);
2639 default_context_.set_network_delegate(&network_delegate);
2640 TestDelegate d;
2641 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2642 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472643 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst0513c9d2015-04-01 05:53:152644 req->Start();
2645 base::RunLoop().Run();
2646
2647 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2648 std::string::npos);
2649 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2650 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2651 }
2652
2653 // Verify that the cookie is also sent for non-first-party requests.
2654 {
2655 TestNetworkDelegate network_delegate;
2656 network_delegate.set_first_party_only_cookies_enabled(false);
2657 default_context_.set_network_delegate(&network_delegate);
2658 TestDelegate d;
2659 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2660 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2661 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2662 req->Start();
2663 base::RunLoop().Run();
2664
2665 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2666 std::string::npos);
2667 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2668 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2669 }
2670}
2671
[email protected]5095cd72012-11-01 10:29:162672// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2673// value for the |fixed_date| argument given to the constructor.
2674class FixedDateNetworkDelegate : public TestNetworkDelegate {
2675 public:
2676 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2677 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:202678 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:162679
[email protected]cba24642014-08-15 20:49:592680 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:202681 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592682 URLRequest* request,
2683 const CompletionCallback& callback,
2684 const HttpResponseHeaders* original_response_headers,
2685 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:132686 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:162687
2688 private:
2689 std::string fixed_date_;
2690
2691 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2692};
2693
2694int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592695 URLRequest* request,
2696 const CompletionCallback& callback,
2697 const HttpResponseHeaders* original_response_headers,
2698 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:162699 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:592700 HttpResponseHeaders* new_response_headers =
2701 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:162702
2703 new_response_headers->RemoveHeader("Date");
2704 new_response_headers->AddHeader("Date: " + fixed_date_);
2705
2706 *override_response_headers = new_response_headers;
2707 return TestNetworkDelegate::OnHeadersReceived(request,
2708 callback,
2709 original_response_headers,
[email protected]5f714132014-03-26 10:41:162710 override_response_headers,
2711 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:162712}
2713
2714// Test that cookie expiration times are adjusted for server/client clock
2715// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2716// headers by defaulting to GMT. (crbug.com/135131)
2717TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2718 LocalHttpTestServer test_server;
2719 ASSERT_TRUE(test_server.Start());
2720
2721 // Set up an expired cookie.
2722 {
2723 TestNetworkDelegate network_delegate;
2724 default_context_.set_network_delegate(&network_delegate);
2725 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192726 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192727 test_server.GetURL(
2728 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362729 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192730 req->Start();
[email protected]255620da2013-08-19 13:14:292731 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162732 }
2733 // Verify that the cookie is not set.
2734 {
2735 TestNetworkDelegate network_delegate;
2736 default_context_.set_network_delegate(&network_delegate);
2737 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192738 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362739 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192740 req->Start();
[email protected]255620da2013-08-19 13:14:292741 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162742
2743 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2744 }
2745 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2746 {
2747 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2748 default_context_.set_network_delegate(&network_delegate);
2749 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192750 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192751 test_server.GetURL(
2752 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362753 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192754 req->Start();
[email protected]255620da2013-08-19 13:14:292755 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162756 }
2757 // Verify that the cookie is set.
2758 {
2759 TestNetworkDelegate network_delegate;
2760 default_context_.set_network_delegate(&network_delegate);
2761 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192762 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362763 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192764 req->Start();
[email protected]255620da2013-08-19 13:14:292765 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162766
2767 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2768 }
2769}
2770
2771
[email protected]316c1e5e2012-09-12 15:17:442772// Check that it is impossible to change the referrer in the extra headers of
2773// an URLRequest.
2774TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2775 LocalHttpTestServer test_server;
2776 ASSERT_TRUE(test_server.Start());
2777
2778 // If extra headers contain referer and the request contains a referer,
2779 // only the latter shall be respected.
2780 {
2781 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192782 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362783 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192784 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442785
2786 HttpRequestHeaders headers;
2787 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192788 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:442789
[email protected]f7022f32014-08-21 16:32:192790 req->Start();
[email protected]255620da2013-08-19 13:14:292791 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442792
2793 EXPECT_EQ("http://foo.com/", d.data_received());
2794 }
2795
2796 // If extra headers contain a referer but the request does not, no referer
2797 // shall be sent in the header.
2798 {
2799 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192800 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362801 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442802
2803 HttpRequestHeaders headers;
2804 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192805 req->SetExtraRequestHeaders(headers);
2806 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:442807
[email protected]f7022f32014-08-21 16:32:192808 req->Start();
[email protected]255620da2013-08-19 13:14:292809 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442810
2811 EXPECT_EQ("None", d.data_received());
2812 }
2813}
2814
[email protected]b89290212009-08-14 22:37:352815class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112816 public:
2817 URLRequestTestHTTP()
[email protected]6cdfd7f2013-02-08 20:40:152818 : test_server_(base::FilePath(FILE_PATH_LITERAL(
[email protected]95409e12010-08-17 20:07:112819 "net/data/url_request_unittest"))) {
2820 }
2821
[email protected]b89290212009-08-14 22:37:352822 protected:
[email protected]21184962011-10-26 00:50:302823 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2824 // |request_method| is the method to use for the initial request.
2825 // |redirect_method| is the method that is expected to be used for the second
2826 // request, after redirection.
2827 // If |include_data| is true, data is uploaded with the request. The
2828 // response body is expected to match it exactly, if and only if
2829 // |request_method| == |redirect_method|.
2830 void HTTPRedirectMethodTest(const GURL& redirect_url,
2831 const std::string& request_method,
2832 const std::string& redirect_method,
2833 bool include_data) {
2834 static const char kData[] = "hello world";
2835 TestDelegate d;
davidben151423e2015-03-23 18:48:362836 scoped_ptr<URLRequest> req(
2837 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192838 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:302839 if (include_data) {
mmenkecbc2b712014-10-09 20:29:072840 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:302841 HttpRequestHeaders headers;
2842 headers.SetHeader(HttpRequestHeaders::kContentLength,
2843 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:192844 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:302845 }
[email protected]f7022f32014-08-21 16:32:192846 req->Start();
[email protected]255620da2013-08-19 13:14:292847 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:192848 EXPECT_EQ(redirect_method, req->method());
2849 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
2850 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:302851 if (include_data) {
2852 if (request_method == redirect_method) {
2853 EXPECT_EQ(kData, d.data_received());
2854 } else {
2855 EXPECT_NE(kData, d.data_received());
2856 }
2857 }
2858 if (HasFailure())
2859 LOG(WARNING) << "Request method was: " << request_method;
2860 }
2861
jww5fe460ff2015-03-28 00:22:512862 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2863 // |request_method| is the method to use for the initial request.
2864 // |redirect_method| is the method that is expected to be used for the second
2865 // request, after redirection.
2866 // |origin_value| is the expected value for the Origin header after
2867 // redirection. If empty, expects that there will be no Origin header.
2868 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
2869 const std::string& request_method,
2870 const std::string& redirect_method,
2871 const std::string& origin_value) {
2872 TestDelegate d;
2873 scoped_ptr<URLRequest> req(
2874 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
2875 req->set_method(request_method);
2876 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
2877 redirect_url.GetOrigin().spec(), false);
2878 req->Start();
2879
2880 base::RunLoop().Run();
2881
2882 EXPECT_EQ(redirect_method, req->method());
2883 // Note that there is no check for request success here because, for
2884 // purposes of testing, the request very well may fail. For example, if the
2885 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
2886 // origin, there is not an HTTPS server in this unit test framework, so the
2887 // request would fail. However, that's fine, as long as the request headers
2888 // are in order and pass the checks below.
2889 if (origin_value.empty()) {
2890 EXPECT_FALSE(
2891 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
2892 } else {
2893 std::string origin_header;
2894 EXPECT_TRUE(req->extra_request_headers().GetHeader(
2895 HttpRequestHeaders::kOrigin, &origin_header));
2896 EXPECT_EQ(origin_value, origin_header);
2897 }
2898 }
2899
[email protected]762d2db2010-01-11 19:03:012900 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012901 const int kMsgSize = 20000; // multiple of 10
2902 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482903 char* uploadBytes = new char[kMsgSize+1];
2904 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012905 char marker = 'a';
2906 for (int idx = 0; idx < kMsgSize/10; idx++) {
2907 memcpy(ptr, "----------", 10);
2908 ptr += 10;
2909 if (idx % 100 == 0) {
2910 ptr--;
2911 *ptr++ = marker;
2912 if (++marker > 'z')
2913 marker = 'a';
2914 }
2915 }
2916 uploadBytes[kMsgSize] = '\0';
2917
[email protected]762d2db2010-01-11 19:03:012918 for (int i = 0; i < kIterations; ++i) {
2919 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192920 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362921 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192922 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:012923
mmenkecbc2b712014-10-09 20:29:072924 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:012925
[email protected]f7022f32014-08-21 16:32:192926 r->Start();
2927 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:012928
[email protected]255620da2013-08-19 13:14:292929 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:012930
[email protected]329b68b2012-11-14 17:54:272931 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:192932 << "request failed: " << r->status().status()
2933 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:012934
2935 EXPECT_FALSE(d.received_data_before_response());
2936 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:012937 }
2938 delete[] uploadBytes;
2939 }
2940
[email protected]ef2bf422012-05-11 03:27:092941 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:222942 r->AppendChunkToUpload("a", 1, false);
2943 r->AppendChunkToUpload("bcd", 3, false);
2944 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2945 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2946 r->AppendChunkToUpload("0", 1, false);
2947 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:112948 }
2949
[email protected]ef2bf422012-05-11 03:27:092950 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:112951 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:272952 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:112953 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2954
[email protected]329b68b2012-11-14 17:54:272955 ASSERT_EQ(1, d->response_started_count())
2956 << "request failed: " << r->status().status()
2957 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:112958
2959 EXPECT_FALSE(d->received_data_before_response());
2960
[email protected]329b68b2012-11-14 17:54:272961 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2962 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:112963 }
2964
[email protected]ede03212012-09-07 12:52:262965 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:342966 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192967 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2968 test_server_.GetURL("set-many-cookies?" +
davidben151423e2015-03-23 18:48:362969 base::IntToString(num_cookies)),
2970 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:342971
[email protected]f7022f32014-08-21 16:32:192972 r->Start();
2973 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:342974
[email protected]255620da2013-08-19 13:14:292975 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:342976
[email protected]f7022f32014-08-21 16:32:192977 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:342978
[email protected]ede03212012-09-07 12:52:262979 if (!is_success) {
[email protected]f7022f32014-08-21 16:32:192980 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:342981 // The test server appears to be unable to handle subsequent requests
2982 // after this error is triggered. Force it to restart.
2983 EXPECT_TRUE(test_server_.Stop());
2984 EXPECT_TRUE(test_server_.Start());
2985 }
2986
2987 return is_success;
2988 }
2989
bengr1bf8e942014-11-07 01:36:502990 LocalHttpTestServer* test_server() {
2991 return &test_server_;
2992 }
2993
2994 protected:
[email protected]1700c6a2012-02-22 18:07:072995 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:352996};
2997
[email protected]95409e12010-08-17 20:07:112998// In this unit test, we're using the HTTPTestServer as a proxy server and
2999// issuing a CONNECT request with the magic host name "www.redirect.com".
3000// The HTTPTestServer will return a 302 response, which we should not
3001// follow.
[email protected]f2f31b32013-01-16 23:24:093002TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:113003 ASSERT_TRUE(test_server_.Start());
3004
[email protected]ceefd7fd2012-11-29 00:36:243005 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043006 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193007 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503008
[email protected]d1ec59082009-02-11 02:48:153009 TestDelegate d;
3010 {
[email protected]f7022f32014-08-21 16:32:193011 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363012 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193013 r->Start();
3014 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153015
[email protected]255620da2013-08-19 13:14:293016 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153017
[email protected]f7022f32014-08-21 16:32:193018 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153019 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193020 EXPECT_TRUE(r->proxy_server().IsEmpty());
3021 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083022 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153023 // We should not have followed the redirect.
3024 EXPECT_EQ(0, d.received_redirect_count());
3025 }
3026}
3027
[email protected]8202d0c2011-02-23 08:31:143028// This is the same as the previous test, but checks that the network delegate
3029// registers the error.
[email protected]c044616e2013-02-20 02:01:263030TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:143031 ASSERT_TRUE(test_server_.Start());
3032
[email protected]ceefd7fd2012-11-29 00:36:243033 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043034 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193035 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503036
[email protected]8202d0c2011-02-23 08:31:143037 TestDelegate d;
3038 {
[email protected]f7022f32014-08-21 16:32:193039 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363040 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193041 r->Start();
3042 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143043
[email protected]255620da2013-08-19 13:14:293044 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143045
[email protected]f7022f32014-08-21 16:32:193046 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153047 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193048 EXPECT_TRUE(r->proxy_server().IsEmpty());
3049 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143050 EXPECT_EQ(1, d.response_started_count());
3051 // We should not have followed the redirect.
3052 EXPECT_EQ(0, d.received_redirect_count());
3053
3054 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053055 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143056 }
3057}
3058
[email protected]dc5a5cf2012-09-26 02:49:303059// Tests that we can block and asynchronously return OK in various stages.
3060TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3061 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3062 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3063 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3064 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3065 };
3066 static const size_t blocking_stages_length = arraysize(blocking_stages);
3067
3068 ASSERT_TRUE(test_server_.Start());
3069
3070 TestDelegate d;
3071 BlockingNetworkDelegate network_delegate(
3072 BlockingNetworkDelegate::USER_CALLBACK);
3073 network_delegate.set_block_on(
3074 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3075 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3076 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3077
3078 TestURLRequestContext context(true);
3079 context.set_network_delegate(&network_delegate);
3080 context.Init();
3081
3082 {
[email protected]f7022f32014-08-21 16:32:193083 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363084 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303085
[email protected]f7022f32014-08-21 16:32:193086 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303087 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293088 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303089 EXPECT_EQ(blocking_stages[i],
3090 network_delegate.stage_blocked_for_callback());
3091 network_delegate.DoCallback(OK);
3092 }
[email protected]255620da2013-08-19 13:14:293093 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193094 EXPECT_EQ(200, r->GetResponseCode());
3095 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303096 EXPECT_EQ(1, network_delegate.created_requests());
3097 EXPECT_EQ(0, network_delegate.destroyed_requests());
3098 }
3099 EXPECT_EQ(1, network_delegate.destroyed_requests());
3100}
3101
[email protected]4c76d7c2011-04-15 19:14:123102// Tests that the network delegate can block and cancel a request.
3103TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
3104 ASSERT_TRUE(test_server_.Start());
3105
3106 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303107 BlockingNetworkDelegate network_delegate(
3108 BlockingNetworkDelegate::AUTO_CALLBACK);
3109 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3110 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123111
[email protected]d5a4dd62012-05-23 01:41:043112 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193113 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503114
[email protected]4c76d7c2011-04-15 19:14:123115 {
[email protected]f7022f32014-08-21 16:32:193116 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363117 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123118
[email protected]f7022f32014-08-21 16:32:193119 r->Start();
[email protected]255620da2013-08-19 13:14:293120 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123121
[email protected]f7022f32014-08-21 16:32:193122 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153123 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193124 EXPECT_TRUE(r->proxy_server().IsEmpty());
3125 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123126 EXPECT_EQ(1, network_delegate.created_requests());
3127 EXPECT_EQ(0, network_delegate.destroyed_requests());
3128 }
3129 EXPECT_EQ(1, network_delegate.destroyed_requests());
3130}
3131
[email protected]b4438d32012-09-27 06:15:303132// Helper function for NetworkDelegateCancelRequestAsynchronously and
3133// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3134// delegate operating in |block_mode| and a request for |url|. It blocks the
3135// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3136void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3137 BlockingNetworkDelegate::Stage stage,
3138 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363139 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303140 BlockingNetworkDelegate network_delegate(block_mode);
3141 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3142 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363143
[email protected]b4438d32012-09-27 06:15:303144 TestURLRequestContext context(true);
3145 context.set_network_delegate(&network_delegate);
3146 context.Init();
[email protected]3cd384c602011-08-31 16:12:363147
3148 {
davidben151423e2015-03-23 18:48:363149 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363150
[email protected]f7022f32014-08-21 16:32:193151 r->Start();
[email protected]255620da2013-08-19 13:14:293152 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363153
[email protected]f7022f32014-08-21 16:32:193154 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153155 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193156 EXPECT_TRUE(r->proxy_server().IsEmpty());
3157 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363158 EXPECT_EQ(1, network_delegate.created_requests());
3159 EXPECT_EQ(0, network_delegate.destroyed_requests());
3160 }
3161 EXPECT_EQ(1, network_delegate.destroyed_requests());
3162}
3163
[email protected]b4438d32012-09-27 06:15:303164// The following 3 tests check that the network delegate can cancel a request
3165// synchronously in various stages of the request.
3166TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
3167 ASSERT_TRUE(test_server_.Start());
3168 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3169 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453170 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303171}
3172
3173TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
3174 ASSERT_TRUE(test_server_.Start());
3175 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3176 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453177 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303178}
3179
3180TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
3181 ASSERT_TRUE(test_server_.Start());
3182 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3183 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453184 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303185}
3186
3187// The following 3 tests check that the network delegate can cancel a request
3188// asynchronously in various stages of the request.
3189TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
3190 ASSERT_TRUE(test_server_.Start());
3191 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3192 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453193 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303194}
3195
3196TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
3197 ASSERT_TRUE(test_server_.Start());
3198 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3199 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453200 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303201}
3202
3203TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
3204 ASSERT_TRUE(test_server_.Start());
3205 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3206 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453207 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303208}
3209
[email protected]4c76d7c2011-04-15 19:14:123210// Tests that the network delegate can block and redirect a request to a new
3211// URL.
3212TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
3213 ASSERT_TRUE(test_server_.Start());
3214
3215 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303216 BlockingNetworkDelegate network_delegate(
3217 BlockingNetworkDelegate::AUTO_CALLBACK);
3218 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:123219 GURL redirect_url(test_server_.GetURL("simple.html"));
3220 network_delegate.set_redirect_url(redirect_url);
3221
[email protected]d5a4dd62012-05-23 01:41:043222 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193223 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503224
[email protected]4c76d7c2011-04-15 19:14:123225 {
[email protected]8f1ac082011-04-19 21:14:133226 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363227 scoped_ptr<URLRequest> r(
3228 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123229
[email protected]6be6fa92014-08-06 23:44:563230 // Quit after hitting the redirect, so can check the headers.
3231 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193232 r->Start();
[email protected]255620da2013-08-19 13:14:293233 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123234
[email protected]6be6fa92014-08-06 23:44:563235 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193236 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3237 EXPECT_EQ(307, r->GetResponseCode());
3238 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563239 std::string location;
[email protected]f7022f32014-08-21 16:32:193240 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3241 &location));
[email protected]6be6fa92014-08-06 23:44:563242 EXPECT_EQ(redirect_url, GURL(location));
3243
3244 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193245 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563246 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193247 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3248 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273249 EXPECT_EQ(
3250 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3251 EXPECT_TRUE(
3252 network_delegate.last_observed_proxy().Equals(
3253 test_server_.host_port_pair()));
3254
[email protected]f7022f32014-08-21 16:32:193255 EXPECT_EQ(0, r->status().error());
3256 EXPECT_EQ(redirect_url, r->url());
3257 EXPECT_EQ(original_url, r->original_url());
3258 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123259 EXPECT_EQ(1, network_delegate.created_requests());
3260 EXPECT_EQ(0, network_delegate.destroyed_requests());
3261 }
3262 EXPECT_EQ(1, network_delegate.destroyed_requests());
3263}
3264
[email protected]b813ed72012-04-05 08:21:363265// Tests that the network delegate can block and redirect a request to a new
3266// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3267TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
3268 ASSERT_TRUE(test_server_.Start());
3269
3270 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303271 BlockingNetworkDelegate network_delegate(
3272 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:363273 GURL redirect_url(test_server_.GetURL("simple.html"));
3274 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363275
[email protected]d5a4dd62012-05-23 01:41:043276 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193277 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363278
3279 {
3280 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363281 scoped_ptr<URLRequest> r(
3282 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363283
[email protected]6be6fa92014-08-06 23:44:563284 // Quit after hitting the redirect, so can check the headers.
3285 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193286 r->Start();
[email protected]255620da2013-08-19 13:14:293287 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363288
[email protected]6be6fa92014-08-06 23:44:563289 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193290 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3291 EXPECT_EQ(307, r->GetResponseCode());
3292 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563293 std::string location;
[email protected]f7022f32014-08-21 16:32:193294 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3295 &location));
[email protected]6be6fa92014-08-06 23:44:563296 EXPECT_EQ(redirect_url, GURL(location));
3297
3298 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193299 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563300 base::RunLoop().Run();
3301
[email protected]f7022f32014-08-21 16:32:193302 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3303 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273304 EXPECT_EQ(
3305 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3306 EXPECT_TRUE(
3307 network_delegate.last_observed_proxy().Equals(
3308 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193309 EXPECT_EQ(0, r->status().error());
3310 EXPECT_EQ(redirect_url, r->url());
3311 EXPECT_EQ(original_url, r->original_url());
3312 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363313 EXPECT_EQ(1, network_delegate.created_requests());
3314 EXPECT_EQ(0, network_delegate.destroyed_requests());
3315 }
3316 EXPECT_EQ(1, network_delegate.destroyed_requests());
3317}
3318
[email protected]3c5ca8c2011-09-29 01:14:513319// Tests that redirects caused by the network delegate preserve POST data.
3320TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3321 ASSERT_TRUE(test_server_.Start());
3322
3323 const char kData[] = "hello world";
3324
3325 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303326 BlockingNetworkDelegate network_delegate(
3327 BlockingNetworkDelegate::AUTO_CALLBACK);
3328 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:513329 GURL redirect_url(test_server_.GetURL("echo"));
3330 network_delegate.set_redirect_url(redirect_url);
3331
[email protected]ef2bf422012-05-11 03:27:093332 TestURLRequestContext context(true);
3333 context.set_network_delegate(&network_delegate);
3334 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513335
3336 {
3337 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363338 scoped_ptr<URLRequest> r(
3339 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193340 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073341 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513342 HttpRequestHeaders headers;
3343 headers.SetHeader(HttpRequestHeaders::kContentLength,
3344 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193345 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563346
3347 // Quit after hitting the redirect, so can check the headers.
3348 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193349 r->Start();
[email protected]255620da2013-08-19 13:14:293350 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513351
[email protected]6be6fa92014-08-06 23:44:563352 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193353 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3354 EXPECT_EQ(307, r->GetResponseCode());
3355 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563356 std::string location;
[email protected]f7022f32014-08-21 16:32:193357 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3358 &location));
[email protected]6be6fa92014-08-06 23:44:563359 EXPECT_EQ(redirect_url, GURL(location));
3360
3361 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193362 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563363 base::RunLoop().Run();
3364
[email protected]f7022f32014-08-21 16:32:193365 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3366 EXPECT_EQ(0, r->status().error());
3367 EXPECT_EQ(redirect_url, r->url());
3368 EXPECT_EQ(original_url, r->original_url());
3369 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513370 EXPECT_EQ(1, network_delegate.created_requests());
3371 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193372 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513373 EXPECT_EQ(kData, d.data_received());
3374 }
3375 EXPECT_EQ(1, network_delegate.destroyed_requests());
3376}
3377
[email protected]5f714132014-03-26 10:41:163378// Tests that the network delegate can block and redirect a request to a new
3379// URL during OnHeadersReceived.
3380TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3381 ASSERT_TRUE(test_server_.Start());
3382
3383 TestDelegate d;
3384 BlockingNetworkDelegate network_delegate(
3385 BlockingNetworkDelegate::AUTO_CALLBACK);
3386 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3387 GURL redirect_url(test_server_.GetURL("simple.html"));
3388 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3389
3390 TestURLRequestContextWithProxy context(
3391 test_server_.host_port_pair().ToString(), &network_delegate);
3392
3393 {
3394 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363395 scoped_ptr<URLRequest> r(
3396 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163397
[email protected]f7022f32014-08-21 16:32:193398 r->Start();
[email protected]5f714132014-03-26 10:41:163399 base::RunLoop().Run();
3400
[email protected]f7022f32014-08-21 16:32:193401 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3402 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273403 EXPECT_EQ(
3404 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3405 EXPECT_TRUE(
3406 network_delegate.last_observed_proxy().Equals(
3407 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193408
3409 EXPECT_EQ(OK, r->status().error());
3410 EXPECT_EQ(redirect_url, r->url());
3411 EXPECT_EQ(original_url, r->original_url());
3412 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163413 EXPECT_EQ(2, network_delegate.created_requests());
3414 EXPECT_EQ(0, network_delegate.destroyed_requests());
3415 }
3416 EXPECT_EQ(1, network_delegate.destroyed_requests());
3417}
3418
[email protected]c2911d72011-10-03 22:16:363419// Tests that the network delegate can synchronously complete OnAuthRequired
3420// by taking no action. This indicates that the NetworkDelegate does not want to
3421// handle the challenge, and is passing the buck along to the
3422// URLRequest::Delegate.
3423TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3424 ASSERT_TRUE(test_server_.Start());
3425
3426 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303427 BlockingNetworkDelegate network_delegate(
3428 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363429
[email protected]ef2bf422012-05-11 03:27:093430 TestURLRequestContext context(true);
3431 context.set_network_delegate(&network_delegate);
3432 context.Init();
[email protected]c2911d72011-10-03 22:16:363433
[email protected]f3cf9802011-10-28 18:44:583434 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363435
3436 {
3437 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363438 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193439 r->Start();
[email protected]79e1fd62013-06-20 06:50:043440
[email protected]255620da2013-08-19 13:14:293441 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043442
[email protected]f7022f32014-08-21 16:32:193443 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3444 EXPECT_EQ(0, r->status().error());
3445 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043446 EXPECT_TRUE(d.auth_required_called());
3447 EXPECT_EQ(1, network_delegate.created_requests());
3448 EXPECT_EQ(0, network_delegate.destroyed_requests());
3449 }
3450 EXPECT_EQ(1, network_delegate.destroyed_requests());
3451}
3452
3453TEST_F(URLRequestTestHTTP,
3454 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3455 ASSERT_TRUE(test_server_.Start());
3456
3457 TestDelegate d;
3458 BlockingNetworkDelegate network_delegate(
3459 BlockingNetworkDelegate::SYNCHRONOUS);
3460
3461 TestURLRequestContext context(true);
3462 context.set_network_delegate(&network_delegate);
3463 context.Init();
3464
3465 d.set_credentials(AuthCredentials(kUser, kSecret));
3466
3467 {
3468 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363469 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193470 r->Start();
[email protected]79e1fd62013-06-20 06:50:043471
3472 {
3473 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193474 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043475 EXPECT_FALSE(headers.HasHeader("Authorization"));
3476 }
3477
[email protected]255620da2013-08-19 13:14:293478 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363479
[email protected]f7022f32014-08-21 16:32:193480 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3481 EXPECT_EQ(0, r->status().error());
3482 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363483 EXPECT_TRUE(d.auth_required_called());
3484 EXPECT_EQ(1, network_delegate.created_requests());
3485 EXPECT_EQ(0, network_delegate.destroyed_requests());
3486 }
3487 EXPECT_EQ(1, network_delegate.destroyed_requests());
3488}
3489
3490// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403491// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363492TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3493 ASSERT_TRUE(test_server_.Start());
3494
3495 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303496 BlockingNetworkDelegate network_delegate(
3497 BlockingNetworkDelegate::SYNCHRONOUS);
3498 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363499 network_delegate.set_auth_retval(
3500 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3501
[email protected]f3cf9802011-10-28 18:44:583502 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363503
[email protected]ef2bf422012-05-11 03:27:093504 TestURLRequestContext context(true);
3505 context.set_network_delegate(&network_delegate);
3506 context.Init();
[email protected]c2911d72011-10-03 22:16:363507
3508 {
3509 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363510 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193511 r->Start();
[email protected]255620da2013-08-19 13:14:293512 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363513
[email protected]f7022f32014-08-21 16:32:193514 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3515 EXPECT_EQ(0, r->status().error());
3516 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363517 EXPECT_FALSE(d.auth_required_called());
3518 EXPECT_EQ(1, network_delegate.created_requests());
3519 EXPECT_EQ(0, network_delegate.destroyed_requests());
3520 }
3521 EXPECT_EQ(1, network_delegate.destroyed_requests());
3522}
3523
[email protected]79e1fd62013-06-20 06:50:043524// Same as above, but also tests that GetFullRequestHeaders returns the proper
3525// headers (for the first or second request) when called at the proper times.
3526TEST_F(URLRequestTestHTTP,
3527 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3528 ASSERT_TRUE(test_server_.Start());
3529
3530 TestDelegate d;
3531 BlockingNetworkDelegate network_delegate(
3532 BlockingNetworkDelegate::SYNCHRONOUS);
3533 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3534 network_delegate.set_auth_retval(
3535 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3536
3537 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3538
3539 TestURLRequestContext context(true);
3540 context.set_network_delegate(&network_delegate);
3541 context.Init();
3542
3543 {
3544 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363545 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193546 r->Start();
[email protected]255620da2013-08-19 13:14:293547 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043548
[email protected]f7022f32014-08-21 16:32:193549 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3550 EXPECT_EQ(0, r->status().error());
3551 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043552 EXPECT_FALSE(d.auth_required_called());
3553 EXPECT_EQ(1, network_delegate.created_requests());
3554 EXPECT_EQ(0, network_delegate.destroyed_requests());
3555
3556 {
3557 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193558 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043559 EXPECT_TRUE(headers.HasHeader("Authorization"));
3560 }
3561 }
3562 EXPECT_EQ(1, network_delegate.destroyed_requests());
3563}
3564
[email protected]c2911d72011-10-03 22:16:363565// Tests that the network delegate can synchronously complete OnAuthRequired
3566// by cancelling authentication.
3567TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3568 ASSERT_TRUE(test_server_.Start());
3569
3570 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303571 BlockingNetworkDelegate network_delegate(
3572 BlockingNetworkDelegate::SYNCHRONOUS);
3573 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363574 network_delegate.set_auth_retval(
3575 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3576
[email protected]ef2bf422012-05-11 03:27:093577 TestURLRequestContext context(true);
3578 context.set_network_delegate(&network_delegate);
3579 context.Init();
[email protected]c2911d72011-10-03 22:16:363580
3581 {
3582 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363583 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193584 r->Start();
[email protected]255620da2013-08-19 13:14:293585 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363586
[email protected]f7022f32014-08-21 16:32:193587 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3588 EXPECT_EQ(OK, r->status().error());
3589 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363590 EXPECT_FALSE(d.auth_required_called());
3591 EXPECT_EQ(1, network_delegate.created_requests());
3592 EXPECT_EQ(0, network_delegate.destroyed_requests());
3593 }
3594 EXPECT_EQ(1, network_delegate.destroyed_requests());
3595}
3596
3597// Tests that the network delegate can asynchronously complete OnAuthRequired
3598// by taking no action. This indicates that the NetworkDelegate does not want
3599// to handle the challenge, and is passing the buck along to the
3600// URLRequest::Delegate.
3601TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3602 ASSERT_TRUE(test_server_.Start());
3603
3604 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303605 BlockingNetworkDelegate network_delegate(
3606 BlockingNetworkDelegate::AUTO_CALLBACK);
3607 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363608
[email protected]ef2bf422012-05-11 03:27:093609 TestURLRequestContext context(true);
3610 context.set_network_delegate(&network_delegate);
3611 context.Init();
[email protected]c2911d72011-10-03 22:16:363612
[email protected]f3cf9802011-10-28 18:44:583613 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363614
3615 {
3616 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363617 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193618 r->Start();
[email protected]255620da2013-08-19 13:14:293619 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363620
[email protected]f7022f32014-08-21 16:32:193621 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3622 EXPECT_EQ(0, r->status().error());
3623 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363624 EXPECT_TRUE(d.auth_required_called());
3625 EXPECT_EQ(1, network_delegate.created_requests());
3626 EXPECT_EQ(0, network_delegate.destroyed_requests());
3627 }
3628 EXPECT_EQ(1, network_delegate.destroyed_requests());
3629}
3630
3631// Tests that the network delegate can asynchronously complete OnAuthRequired
3632// by setting credentials.
3633TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3634 ASSERT_TRUE(test_server_.Start());
3635
3636 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303637 BlockingNetworkDelegate network_delegate(
3638 BlockingNetworkDelegate::AUTO_CALLBACK);
3639 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363640 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363641 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3642
[email protected]f3cf9802011-10-28 18:44:583643 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363644 network_delegate.set_auth_credentials(auth_credentials);
3645
[email protected]ef2bf422012-05-11 03:27:093646 TestURLRequestContext context(true);
3647 context.set_network_delegate(&network_delegate);
3648 context.Init();
[email protected]c2911d72011-10-03 22:16:363649
3650 {
3651 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363652 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193653 r->Start();
[email protected]255620da2013-08-19 13:14:293654 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363655
[email protected]f7022f32014-08-21 16:32:193656 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3657 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:363658
[email protected]f7022f32014-08-21 16:32:193659 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363660 EXPECT_FALSE(d.auth_required_called());
3661 EXPECT_EQ(1, network_delegate.created_requests());
3662 EXPECT_EQ(0, network_delegate.destroyed_requests());
3663 }
3664 EXPECT_EQ(1, network_delegate.destroyed_requests());
3665}
3666
3667// Tests that the network delegate can asynchronously complete OnAuthRequired
3668// by cancelling authentication.
3669TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3670 ASSERT_TRUE(test_server_.Start());
3671
3672 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303673 BlockingNetworkDelegate network_delegate(
3674 BlockingNetworkDelegate::AUTO_CALLBACK);
3675 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363676 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363677 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3678
[email protected]ef2bf422012-05-11 03:27:093679 TestURLRequestContext context(true);
3680 context.set_network_delegate(&network_delegate);
3681 context.Init();
[email protected]c2911d72011-10-03 22:16:363682
3683 {
3684 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363685 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193686 r->Start();
[email protected]255620da2013-08-19 13:14:293687 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363688
[email protected]f7022f32014-08-21 16:32:193689 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3690 EXPECT_EQ(OK, r->status().error());
3691 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363692 EXPECT_FALSE(d.auth_required_called());
3693 EXPECT_EQ(1, network_delegate.created_requests());
3694 EXPECT_EQ(0, network_delegate.destroyed_requests());
3695 }
3696 EXPECT_EQ(1, network_delegate.destroyed_requests());
3697}
3698
[email protected]9045b8822012-01-13 20:35:353699// Tests that we can handle when a network request was canceled while we were
3700// waiting for the network delegate.
3701// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3702TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3703 ASSERT_TRUE(test_server_.Start());
3704
3705 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303706 BlockingNetworkDelegate network_delegate(
3707 BlockingNetworkDelegate::USER_CALLBACK);
3708 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353709
[email protected]ef2bf422012-05-11 03:27:093710 TestURLRequestContext context(true);
3711 context.set_network_delegate(&network_delegate);
3712 context.Init();
[email protected]9045b8822012-01-13 20:35:353713
3714 {
[email protected]f7022f32014-08-21 16:32:193715 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363716 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353717
[email protected]f7022f32014-08-21 16:32:193718 r->Start();
[email protected]255620da2013-08-19 13:14:293719 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303720 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3721 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353722 EXPECT_EQ(0, network_delegate.completed_requests());
3723 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193724 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353725 // Ensure that network delegate is notified.
3726 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193727 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3728 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353729 EXPECT_EQ(1, network_delegate.created_requests());
3730 EXPECT_EQ(0, network_delegate.destroyed_requests());
3731 }
3732 EXPECT_EQ(1, network_delegate.destroyed_requests());
3733}
3734
3735// Tests that we can handle when a network request was canceled while we were
3736// waiting for the network delegate.
3737// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3738TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3739 ASSERT_TRUE(test_server_.Start());
3740
3741 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303742 BlockingNetworkDelegate network_delegate(
3743 BlockingNetworkDelegate::USER_CALLBACK);
3744 network_delegate.set_block_on(
3745 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:353746
[email protected]ef2bf422012-05-11 03:27:093747 TestURLRequestContext context(true);
3748 context.set_network_delegate(&network_delegate);
3749 context.Init();
[email protected]9045b8822012-01-13 20:35:353750
3751 {
[email protected]f7022f32014-08-21 16:32:193752 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363753 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353754
[email protected]f7022f32014-08-21 16:32:193755 r->Start();
[email protected]255620da2013-08-19 13:14:293756 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303757 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3758 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353759 EXPECT_EQ(0, network_delegate.completed_requests());
3760 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193761 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353762 // Ensure that network delegate is notified.
3763 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193764 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3765 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353766 EXPECT_EQ(1, network_delegate.created_requests());
3767 EXPECT_EQ(0, network_delegate.destroyed_requests());
3768 }
3769 EXPECT_EQ(1, network_delegate.destroyed_requests());
3770}
3771
3772// Tests that we can handle when a network request was canceled while we were
3773// waiting for the network delegate.
3774// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3775TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3776 ASSERT_TRUE(test_server_.Start());
3777
3778 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303779 BlockingNetworkDelegate network_delegate(
3780 BlockingNetworkDelegate::USER_CALLBACK);
3781 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:353782
[email protected]ef2bf422012-05-11 03:27:093783 TestURLRequestContext context(true);
3784 context.set_network_delegate(&network_delegate);
3785 context.Init();
[email protected]9045b8822012-01-13 20:35:353786
3787 {
[email protected]f7022f32014-08-21 16:32:193788 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363789 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353790
[email protected]f7022f32014-08-21 16:32:193791 r->Start();
[email protected]255620da2013-08-19 13:14:293792 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303793 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3794 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353795 EXPECT_EQ(0, network_delegate.completed_requests());
3796 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193797 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353798 // Ensure that network delegate is notified.
3799 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193800 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3801 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353802 EXPECT_EQ(1, network_delegate.created_requests());
3803 EXPECT_EQ(0, network_delegate.destroyed_requests());
3804 }
3805 EXPECT_EQ(1, network_delegate.destroyed_requests());
3806}
3807
3808// Tests that we can handle when a network request was canceled while we were
3809// waiting for the network delegate.
3810// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:023811TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:353812 ASSERT_TRUE(test_server_.Start());
3813
3814 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303815 BlockingNetworkDelegate network_delegate(
3816 BlockingNetworkDelegate::USER_CALLBACK);
3817 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:353818
[email protected]ef2bf422012-05-11 03:27:093819 TestURLRequestContext context(true);
3820 context.set_network_delegate(&network_delegate);
3821 context.Init();
[email protected]9045b8822012-01-13 20:35:353822
3823 {
[email protected]f7022f32014-08-21 16:32:193824 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363825 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353826
[email protected]f7022f32014-08-21 16:32:193827 r->Start();
[email protected]255620da2013-08-19 13:14:293828 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303829 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3830 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353831 EXPECT_EQ(0, network_delegate.completed_requests());
3832 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193833 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353834 // Ensure that network delegate is notified.
3835 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193836 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3837 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353838 EXPECT_EQ(1, network_delegate.created_requests());
3839 EXPECT_EQ(0, network_delegate.destroyed_requests());
3840 }
3841 EXPECT_EQ(1, network_delegate.destroyed_requests());
3842}
3843
[email protected]95409e12010-08-17 20:07:113844// In this unit test, we're using the HTTPTestServer as a proxy server and
3845// issuing a CONNECT request with the magic host name "www.server-auth.com".
3846// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:353847TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:113848 ASSERT_TRUE(test_server_.Start());
3849
[email protected]ceefd7fd2012-11-29 00:36:243850 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043851 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193852 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503853
[email protected]dc651782009-02-14 01:45:083854 TestDelegate d;
3855 {
[email protected]f7022f32014-08-21 16:32:193856 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363857 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:083858
[email protected]f7022f32014-08-21 16:32:193859 r->Start();
3860 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:083861
[email protected]255620da2013-08-19 13:14:293862 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:083863
[email protected]f7022f32014-08-21 16:32:193864 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153865 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193866 EXPECT_TRUE(r->proxy_server().IsEmpty());
3867 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083868 }
3869}
3870
[email protected]b89290212009-08-14 22:37:353871TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:113872 ASSERT_TRUE(test_server_.Start());
3873
initial.commit586acc5fe2008-07-26 22:42:523874 TestDelegate d;
3875 {
[email protected]f7022f32014-08-21 16:32:193876 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363877 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:523878
[email protected]f7022f32014-08-21 16:32:193879 r->Start();
3880 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:523881
[email protected]255620da2013-08-19 13:14:293882 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523883
3884 EXPECT_EQ(1, d.response_started_count());
3885 EXPECT_FALSE(d.received_data_before_response());
3886 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193887 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193888 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:193889 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193890 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:163891
[email protected]9e743cd2010-03-16 07:03:533892 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:523893 }
initial.commit586acc5fe2008-07-26 22:42:523894}
3895
[email protected]263163f2012-06-14 22:40:343896// This test has the server send a large number of cookies to the client.
3897// To ensure that no number of cookies causes a crash, a galloping binary
3898// search is used to estimate that maximum number of cookies that are accepted
3899// by the browser. Beyond the maximum number, the request will fail with
3900// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:303901#if defined(OS_WIN)
3902// http://crbug.com/177916
3903#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3904#else
3905#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3906#endif // defined(OS_WIN)
3907TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:343908 ASSERT_TRUE(test_server_.Start());
3909
3910 int lower_bound = 0;
3911 int upper_bound = 1;
3912
3913 // Double the number of cookies until the response header limits are
3914 // exceeded.
3915 while (DoManyCookiesRequest(upper_bound)) {
3916 lower_bound = upper_bound;
3917 upper_bound *= 2;
3918 ASSERT_LT(upper_bound, 1000000);
3919 }
3920
pkasting6b68a162014-12-01 22:10:293921 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:343922 if (tolerance < 2)
3923 tolerance = 2;
3924
3925 // Perform a binary search to find the highest possible number of cookies,
3926 // within the desired tolerance.
3927 while (upper_bound - lower_bound >= tolerance) {
3928 int num_cookies = (lower_bound + upper_bound) / 2;
3929
3930 if (DoManyCookiesRequest(num_cookies))
3931 lower_bound = num_cookies;
3932 else
3933 upper_bound = num_cookies;
3934 }
3935 // Success: the test did not crash.
3936}
3937
[email protected]b89290212009-08-14 22:37:353938TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:113939 ASSERT_TRUE(test_server_.Start());
3940
initial.commit586acc5fe2008-07-26 22:42:523941 TestDelegate d;
3942 {
[email protected]f7022f32014-08-21 16:32:193943 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363944 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:523945
[email protected]f7022f32014-08-21 16:32:193946 r->Start();
3947 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:523948
[email protected]255620da2013-08-19 13:14:293949 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523950
3951 EXPECT_EQ(1, d.response_started_count());
3952 EXPECT_FALSE(d.received_data_before_response());
3953 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193954 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193955 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:193956 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193957 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:523958 }
[email protected]5d7b373e2009-09-02 07:19:033959}
3960
[email protected]79e1fd62013-06-20 06:50:043961TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3962 ASSERT_TRUE(test_server_.Start());
3963
3964 TestDelegate d;
3965 {
3966 GURL test_url(test_server_.GetURL(std::string()));
davidben151423e2015-03-23 18:48:363967 scoped_ptr<URLRequest> r(
3968 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:043969
3970 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193971 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043972
[email protected]f7022f32014-08-21 16:32:193973 r->Start();
3974 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:043975
[email protected]255620da2013-08-19 13:14:293976 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043977
3978 EXPECT_EQ(1, d.response_started_count());
3979 EXPECT_FALSE(d.received_data_before_response());
3980 EXPECT_NE(0, d.bytes_received());
3981 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193982 r->GetSocketAddress().host());
[email protected]79e1fd62013-06-20 06:50:043983 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193984 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:043985
3986 EXPECT_TRUE(d.have_full_request_headers());
3987 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3988 }
3989}
3990
[email protected]58e32bb2013-01-21 18:23:253991TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3992 ASSERT_TRUE(test_server_.Start());
3993
3994 TestDelegate d;
3995 {
[email protected]f7022f32014-08-21 16:32:193996 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363997 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:253998
[email protected]f7022f32014-08-21 16:32:193999 r->Start();
4000 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254001
[email protected]255620da2013-08-19 13:14:294002 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254003
4004 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194005 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254006 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4007
4008 EXPECT_EQ(1, d.response_started_count());
4009 EXPECT_FALSE(d.received_data_before_response());
4010 EXPECT_NE(0, d.bytes_received());
4011 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194012 r->GetSocketAddress().host());
[email protected]58e32bb2013-01-21 18:23:254013 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194014 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254015 }
4016}
4017
[email protected]aad63572011-05-24 20:14:394018TEST_F(URLRequestTestHTTP, GetZippedTest) {
4019 ASSERT_TRUE(test_server_.Start());
4020
4021 // Parameter that specifies the Content-Length field in the response:
4022 // C - Compressed length.
4023 // U - Uncompressed length.
4024 // L - Large length (larger than both C & U).
4025 // M - Medium length (between C & U).
4026 // S - Small length (smaller than both C & U).
4027 const char test_parameters[] = "CULMS";
4028 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4029 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444030 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394031 // S has too little data, but we seem to accept it.
4032 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374033 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394034
4035 for (int i = 0; i < num_tests ; i++) {
4036 TestDelegate d;
4037 {
4038 std::string test_file =
4039 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
4040 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394041
[email protected]ceefd7fd2012-11-29 00:36:244042 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094043 TestURLRequestContext context(true);
4044 context.set_network_delegate(&network_delegate);
4045 context.Init();
[email protected]87a09a92011-07-14 15:50:504046
[email protected]f7022f32014-08-21 16:32:194047 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364048 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194049 r->Start();
4050 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394051
[email protected]255620da2013-08-19 13:14:294052 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394053
4054 EXPECT_EQ(1, d.response_started_count());
4055 EXPECT_FALSE(d.received_data_before_response());
4056 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194057 << " status = " << r->status().status()
4058 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394059 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194060 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394061 << " Parameter = \"" << test_file << "\"";
4062 } else {
[email protected]f7022f32014-08-21 16:32:194063 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4064 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394065 << " Parameter = \"" << test_file << "\"";
4066 }
4067 }
4068 }
4069}
4070
[email protected]58e32bb2013-01-21 18:23:254071TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
4072 ASSERT_TRUE(test_server_.Start());
4073
[email protected]007b3f82013-04-09 08:46:454074 GURL destination_url = test_server_.GetURL(std::string());
4075 GURL original_url =
4076 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254077 TestDelegate d;
davidben151423e2015-03-23 18:48:364078 scoped_ptr<URLRequest> req(
4079 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194080 req->Start();
[email protected]255620da2013-08-19 13:14:294081 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254082
4083 EXPECT_EQ(1, d.response_started_count());
4084 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194085 EXPECT_EQ(destination_url, req->url());
4086 EXPECT_EQ(original_url, req->original_url());
4087 ASSERT_EQ(2U, req->url_chain().size());
4088 EXPECT_EQ(original_url, req->url_chain()[0]);
4089 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254090
4091 LoadTimingInfo load_timing_info_before_redirect;
4092 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4093 &load_timing_info_before_redirect));
4094 TestLoadTimingNotReused(load_timing_info_before_redirect,
4095 CONNECT_TIMING_HAS_DNS_TIMES);
4096
4097 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194098 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254099 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4100
4101 // Check that a new socket was used on redirect, since the server does not
4102 // supposed keep-alive sockets, and that the times before the redirect are
4103 // before the ones recorded for the second request.
4104 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4105 load_timing_info.socket_log_id);
4106 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4107 load_timing_info.connect_timing.connect_start);
4108}
4109
[email protected]8f1ac082011-04-19 21:14:134110TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
4111 ASSERT_TRUE(test_server_.Start());
4112
[email protected]007b3f82013-04-09 08:46:454113 GURL destination_url = test_server_.GetURL(std::string());
4114 GURL middle_redirect_url =
4115 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:134116 GURL original_url = test_server_.GetURL(
4117 "server-redirect?" + middle_redirect_url.spec());
4118 TestDelegate d;
davidben151423e2015-03-23 18:48:364119 scoped_ptr<URLRequest> req(
4120 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194121 req->Start();
[email protected]255620da2013-08-19 13:14:294122 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134123
4124 EXPECT_EQ(1, d.response_started_count());
4125 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194126 EXPECT_EQ(destination_url, req->url());
4127 EXPECT_EQ(original_url, req->original_url());
4128 ASSERT_EQ(3U, req->url_chain().size());
4129 EXPECT_EQ(original_url, req->url_chain()[0]);
4130 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4131 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134132}
4133
[email protected]abe1c4a2013-10-25 19:28:514134// First and second pieces of information logged by delegates to URLRequests.
4135const char kFirstDelegateInfo[] = "Wonderful delegate";
4136const char kSecondDelegateInfo[] = "Exciting delegate";
4137
4138// Logs delegate information to a URLRequest. The first string is logged
4139// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4140// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4141// another asynchronous call is used to clear the delegate information
4142// before calling a callback. The object then deletes itself.
4143class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4144 public:
4145 typedef base::Callback<void()> Callback;
4146
4147 // Each time delegate information is added to the URLRequest, the resulting
4148 // load state is checked. The expected load state after each request is
4149 // passed in as an argument.
4150 static void Run(URLRequest* url_request,
4151 LoadState expected_first_load_state,
4152 LoadState expected_second_load_state,
4153 LoadState expected_third_load_state,
4154 const Callback& callback) {
4155 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4156 url_request,
4157 expected_first_load_state,
4158 expected_second_load_state,
4159 expected_third_load_state,
4160 callback);
4161 logger->Start();
4162 }
4163
4164 // Checks that the log entries, starting with log_position, contain the
4165 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4166 // recorded. Returns the index of entry after the expected number of
4167 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464168 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514169 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514170 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4171 if (log_position + 3 >= entries.size()) {
4172 ADD_FAILURE() << "Not enough log entries";
4173 return entries.size();
4174 }
4175 std::string delegate_info;
4176 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4177 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4178 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4179 &delegate_info));
4180 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4181
4182 ++log_position;
4183 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4184 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4185
4186 ++log_position;
4187 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4188 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4189 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4190 &delegate_info));
4191 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4192
4193 ++log_position;
4194 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4195 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4196
4197 return log_position + 1;
4198 }
4199
[email protected]1826a402014-01-08 15:40:484200 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4201 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464202 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4203 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484204 log_position =
4205 ExpectLogContainsSomewhereAfter(entries,
4206 log_position,
4207 NetLog::TYPE_URL_REQUEST_DELEGATE,
4208 NetLog::PHASE_BEGIN);
4209 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4210 entries[log_position + 1].type);
4211 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4212 return log_position + 1;
4213 }
4214
[email protected]abe1c4a2013-10-25 19:28:514215 private:
4216 friend class base::RefCounted<AsyncDelegateLogger>;
4217
4218 AsyncDelegateLogger(URLRequest* url_request,
4219 LoadState expected_first_load_state,
4220 LoadState expected_second_load_state,
4221 LoadState expected_third_load_state,
4222 const Callback& callback)
4223 : url_request_(url_request),
4224 expected_first_load_state_(expected_first_load_state),
4225 expected_second_load_state_(expected_second_load_state),
4226 expected_third_load_state_(expected_third_load_state),
4227 callback_(callback) {
4228 }
4229
4230 ~AsyncDelegateLogger() {}
4231
4232 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534233 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514234 LoadStateWithParam load_state = url_request_->GetLoadState();
4235 EXPECT_EQ(expected_first_load_state_, load_state.state);
4236 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
4237 base::MessageLoop::current()->PostTask(
4238 FROM_HERE,
4239 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
4240 }
4241
4242 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534243 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514244 LoadStateWithParam load_state = url_request_->GetLoadState();
4245 EXPECT_EQ(expected_second_load_state_, load_state.state);
4246 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4247 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4248 } else {
4249 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4250 }
4251 base::MessageLoop::current()->PostTask(
4252 FROM_HERE,
4253 base::Bind(&AsyncDelegateLogger::LogComplete, this));
4254 }
4255
4256 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534257 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514258 LoadStateWithParam load_state = url_request_->GetLoadState();
4259 EXPECT_EQ(expected_third_load_state_, load_state.state);
4260 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084261 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514262 callback_.Run();
4263 }
4264
4265 URLRequest* url_request_;
4266 const int expected_first_load_state_;
4267 const int expected_second_load_state_;
4268 const int expected_third_load_state_;
4269 const Callback callback_;
4270
4271 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4272};
4273
4274// NetworkDelegate that logs delegate information before a request is started,
4275// before headers are sent, when headers are read, and when auth information
4276// is requested. Uses AsyncDelegateLogger.
4277class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4278 public:
4279 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204280 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514281
4282 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204283 int OnBeforeURLRequest(URLRequest* request,
4284 const CompletionCallback& callback,
4285 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514286 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4287 return RunCallbackAsynchronously(request, callback);
4288 }
4289
dchengb03027d2014-10-21 12:00:204290 int OnBeforeSendHeaders(URLRequest* request,
4291 const CompletionCallback& callback,
4292 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514293 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4294 return RunCallbackAsynchronously(request, callback);
4295 }
4296
dchengb03027d2014-10-21 12:00:204297 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514298 URLRequest* request,
4299 const CompletionCallback& callback,
4300 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164301 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134302 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164303 TestNetworkDelegate::OnHeadersReceived(request,
4304 callback,
[email protected]abe1c4a2013-10-25 19:28:514305 original_response_headers,
[email protected]5f714132014-03-26 10:41:164306 override_response_headers,
4307 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514308 return RunCallbackAsynchronously(request, callback);
4309 }
4310
dchengb03027d2014-10-21 12:00:204311 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514312 URLRequest* request,
4313 const AuthChallengeInfo& auth_info,
4314 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134315 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514316 AsyncDelegateLogger::Run(
4317 request,
4318 LOAD_STATE_WAITING_FOR_DELEGATE,
4319 LOAD_STATE_WAITING_FOR_DELEGATE,
4320 LOAD_STATE_WAITING_FOR_DELEGATE,
4321 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4322 callback, credentials));
4323 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4324 }
4325
4326 private:
4327 static int RunCallbackAsynchronously(
4328 URLRequest* request,
4329 const CompletionCallback& callback) {
4330 AsyncDelegateLogger::Run(
4331 request,
4332 LOAD_STATE_WAITING_FOR_DELEGATE,
4333 LOAD_STATE_WAITING_FOR_DELEGATE,
4334 LOAD_STATE_WAITING_FOR_DELEGATE,
4335 base::Bind(callback, OK));
4336 return ERR_IO_PENDING;
4337 }
4338
4339 static void SetAuthAndResume(const AuthCallback& callback,
4340 AuthCredentials* credentials) {
4341 *credentials = AuthCredentials(kUser, kSecret);
4342 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4343 }
4344
4345 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4346};
4347
4348// URLRequest::Delegate that logs delegate information when the headers
4349// are received, when each read completes, and during redirects. Uses
4350// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4351//
4352// Inherits from TestDelegate to reuse the TestDelegate code to handle
4353// advancing to the next step in most cases, as well as cancellation.
4354class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4355 public:
4356 enum CancelStage {
4357 NO_CANCEL = 0,
4358 CANCEL_ON_RECEIVED_REDIRECT,
4359 CANCEL_ON_RESPONSE_STARTED,
4360 CANCEL_ON_READ_COMPLETED
4361 };
4362
4363 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4364 : cancel_stage_(cancel_stage) {
4365 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4366 set_cancel_in_received_redirect(true);
4367 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4368 set_cancel_in_response_started(true);
4369 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4370 set_cancel_in_received_data(true);
4371 }
dchengb03027d2014-10-21 12:00:204372 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514373
4374 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204375 void OnReceivedRedirect(URLRequest* request,
4376 const RedirectInfo& redirect_info,
4377 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514378 *defer_redirect = true;
4379 AsyncDelegateLogger::Run(
4380 request,
4381 LOAD_STATE_WAITING_FOR_DELEGATE,
4382 LOAD_STATE_WAITING_FOR_DELEGATE,
4383 LOAD_STATE_WAITING_FOR_DELEGATE,
4384 base::Bind(
4385 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594386 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514387 }
4388
dchengb03027d2014-10-21 12:00:204389 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514390 AsyncDelegateLogger::Run(
4391 request,
4392 LOAD_STATE_WAITING_FOR_DELEGATE,
4393 LOAD_STATE_WAITING_FOR_DELEGATE,
4394 LOAD_STATE_WAITING_FOR_DELEGATE,
4395 base::Bind(
4396 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4397 base::Unretained(this), request));
4398 }
4399
dchengb03027d2014-10-21 12:00:204400 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514401 AsyncDelegateLogger::Run(
4402 request,
4403 LOAD_STATE_IDLE,
4404 LOAD_STATE_IDLE,
4405 LOAD_STATE_IDLE,
4406 base::Bind(
4407 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4408 base::Unretained(this), request, bytes_read));
4409 }
4410
4411 private:
4412 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594413 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514414 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594415 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514416 // FollowDeferredRedirect should not be called after cancellation.
4417 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4418 return;
4419 if (!defer_redirect)
4420 request->FollowDeferredRedirect();
4421 }
4422
4423 void OnResponseStartedLoggingComplete(URLRequest* request) {
4424 // The parent class continues the request.
4425 TestDelegate::OnResponseStarted(request);
4426 }
4427
4428 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4429 // The parent class continues the request.
4430 TestDelegate::OnReadCompleted(request, bytes_read);
4431 }
4432
4433 const CancelStage cancel_stage_;
4434
4435 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4436};
4437
4438// Tests handling of delegate info before a request starts.
4439TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4440 ASSERT_TRUE(test_server_.Start());
4441
4442 TestDelegate request_delegate;
4443 TestURLRequestContext context(true);
4444 context.set_network_delegate(NULL);
4445 context.set_net_log(&net_log_);
4446 context.Init();
4447
4448 {
davidben151423e2015-03-23 18:48:364449 scoped_ptr<URLRequest> r(
4450 context.CreateRequest(test_server_.GetURL("empty.html"),
4451 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194452 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514453 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084454 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514455
4456 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194457 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514458 LOAD_STATE_WAITING_FOR_DELEGATE,
4459 LOAD_STATE_WAITING_FOR_DELEGATE,
4460 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194461 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514462
4463 base::RunLoop().Run();
4464
[email protected]f7022f32014-08-21 16:32:194465 EXPECT_EQ(200, r->GetResponseCode());
4466 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514467 }
4468
mmenke43758e62015-05-04 21:09:464469 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514470 net_log_.GetEntries(&entries);
4471 size_t log_position = ExpectLogContainsSomewhereAfter(
4472 entries,
4473 0,
4474 NetLog::TYPE_DELEGATE_INFO,
4475 NetLog::PHASE_BEGIN);
4476
4477 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4478
4479 // Nothing else should add any delegate info to the request.
4480 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4481 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4482}
4483
4484// Tests handling of delegate info from a network delegate.
4485TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4486 ASSERT_TRUE(test_server_.Start());
4487
4488 TestDelegate request_delegate;
4489 AsyncLoggingNetworkDelegate network_delegate;
4490 TestURLRequestContext context(true);
4491 context.set_network_delegate(&network_delegate);
4492 context.set_net_log(&net_log_);
4493 context.Init();
4494
4495 {
davidben151423e2015-03-23 18:48:364496 scoped_ptr<URLRequest> r(
4497 context.CreateRequest(test_server_.GetURL("simple.html"),
4498 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194499 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514500 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084501 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514502
[email protected]f7022f32014-08-21 16:32:194503 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514504 base::RunLoop().Run();
4505
[email protected]f7022f32014-08-21 16:32:194506 EXPECT_EQ(200, r->GetResponseCode());
4507 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514508 EXPECT_EQ(1, network_delegate.created_requests());
4509 EXPECT_EQ(0, network_delegate.destroyed_requests());
4510 }
4511 EXPECT_EQ(1, network_delegate.destroyed_requests());
4512
4513 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464514 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514515 net_log_.GetEntries(&entries);
4516 for (size_t i = 0; i < 3; ++i) {
4517 log_position = ExpectLogContainsSomewhereAfter(
4518 entries,
4519 log_position + 1,
4520 NetLog::TYPE_URL_REQUEST_DELEGATE,
4521 NetLog::PHASE_BEGIN);
4522
4523 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4524 log_position + 1);
4525
4526 ASSERT_LT(log_position, entries.size());
4527 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4528 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484529
4530 if (i == 1) {
4531 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4532 entries, log_position + 1);
4533 }
[email protected]abe1c4a2013-10-25 19:28:514534 }
4535
4536 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4537 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4538}
4539
4540// Tests handling of delegate info from a network delegate in the case of an
4541// HTTP redirect.
4542TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4543 ASSERT_TRUE(test_server_.Start());
4544
4545 TestDelegate request_delegate;
4546 AsyncLoggingNetworkDelegate network_delegate;
4547 TestURLRequestContext context(true);
4548 context.set_network_delegate(&network_delegate);
4549 context.set_net_log(&net_log_);
4550 context.Init();
4551
4552 {
[email protected]f7022f32014-08-21 16:32:194553 scoped_ptr<URLRequest> r(context.CreateRequest(
4554 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364555 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194556 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514557 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084558 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514559
[email protected]f7022f32014-08-21 16:32:194560 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514561 base::RunLoop().Run();
4562
[email protected]f7022f32014-08-21 16:32:194563 EXPECT_EQ(200, r->GetResponseCode());
4564 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514565 EXPECT_EQ(2, network_delegate.created_requests());
4566 EXPECT_EQ(0, network_delegate.destroyed_requests());
4567 }
4568 EXPECT_EQ(1, network_delegate.destroyed_requests());
4569
4570 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464571 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514572 net_log_.GetEntries(&entries);
4573 // The NetworkDelegate logged information in OnBeforeURLRequest,
4574 // OnBeforeSendHeaders, and OnHeadersReceived.
4575 for (size_t i = 0; i < 3; ++i) {
4576 log_position = ExpectLogContainsSomewhereAfter(
4577 entries,
4578 log_position + 1,
4579 NetLog::TYPE_URL_REQUEST_DELEGATE,
4580 NetLog::PHASE_BEGIN);
4581
4582 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4583 log_position + 1);
4584
4585 ASSERT_LT(log_position, entries.size());
4586 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4587 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484588
4589 if (i == 1) {
4590 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4591 entries, log_position + 1);
4592 }
[email protected]abe1c4a2013-10-25 19:28:514593 }
4594
4595 // The URLRequest::Delegate then gets informed about the redirect.
4596 log_position = ExpectLogContainsSomewhereAfter(
4597 entries,
4598 log_position + 1,
4599 NetLog::TYPE_URL_REQUEST_DELEGATE,
4600 NetLog::PHASE_BEGIN);
4601
4602 // The NetworkDelegate logged information in the same three events as before.
4603 for (size_t i = 0; i < 3; ++i) {
4604 log_position = ExpectLogContainsSomewhereAfter(
4605 entries,
4606 log_position + 1,
4607 NetLog::TYPE_URL_REQUEST_DELEGATE,
4608 NetLog::PHASE_BEGIN);
4609
4610 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4611 log_position + 1);
4612
4613 ASSERT_LT(log_position, entries.size());
4614 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4615 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4616 }
4617
4618 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4619 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4620}
4621
4622// Tests handling of delegate info from a network delegate in the case of HTTP
4623// AUTH.
4624TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4625 ASSERT_TRUE(test_server_.Start());
4626
4627 TestDelegate request_delegate;
4628 AsyncLoggingNetworkDelegate network_delegate;
4629 TestURLRequestContext context(true);
4630 context.set_network_delegate(&network_delegate);
4631 context.set_net_log(&net_log_);
4632 context.Init();
4633
4634 {
davidben151423e2015-03-23 18:48:364635 scoped_ptr<URLRequest> r(
4636 context.CreateRequest(test_server_.GetURL("auth-basic"),
4637 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194638 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514639 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084640 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514641
[email protected]f7022f32014-08-21 16:32:194642 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514643 base::RunLoop().Run();
4644
[email protected]f7022f32014-08-21 16:32:194645 EXPECT_EQ(200, r->GetResponseCode());
4646 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514647 EXPECT_EQ(1, network_delegate.created_requests());
4648 EXPECT_EQ(0, network_delegate.destroyed_requests());
4649 }
4650 EXPECT_EQ(1, network_delegate.destroyed_requests());
4651
4652 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464653 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514654 net_log_.GetEntries(&entries);
4655 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4656 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4657 // OnBeforeURLRequest and OnBeforeSendHeaders.
4658 for (size_t i = 0; i < 6; ++i) {
4659 log_position = ExpectLogContainsSomewhereAfter(
4660 entries,
4661 log_position + 1,
4662 NetLog::TYPE_URL_REQUEST_DELEGATE,
4663 NetLog::PHASE_BEGIN);
4664
4665 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4666 log_position + 1);
4667
4668 ASSERT_LT(log_position, entries.size());
4669 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4670 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484671
4672 if (i == 1) {
4673 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4674 entries, log_position + 1);
4675 }
[email protected]abe1c4a2013-10-25 19:28:514676 }
4677
4678 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4679 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4680}
4681
4682// Tests handling of delegate info from a URLRequest::Delegate.
4683TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4684 ASSERT_TRUE(test_server_.Start());
4685
4686 AsyncLoggingUrlRequestDelegate request_delegate(
4687 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4688 TestURLRequestContext context(true);
4689 context.set_network_delegate(NULL);
4690 context.set_net_log(&net_log_);
4691 context.Init();
4692
4693 {
4694 // A chunked response with delays between chunks is used to make sure that
4695 // attempts by the URLRequest delegate to log information while reading the
4696 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:484697 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:514698 // that it occurs.
[email protected]f7022f32014-08-21 16:32:194699 scoped_ptr<URLRequest> r(context.CreateRequest(
4700 test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364701 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194702 LoadStateWithParam load_state = r->GetLoadState();
4703 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514704 base::RunLoop().Run();
4705
[email protected]f7022f32014-08-21 16:32:194706 EXPECT_EQ(200, r->GetResponseCode());
4707 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514708 }
4709
mmenke43758e62015-05-04 21:09:464710 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514711 net_log_.GetEntries(&entries);
4712
[email protected]1826a402014-01-08 15:40:484713 size_t log_position = 0;
4714
4715 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4716 entries, log_position);
4717
[email protected]abe1c4a2013-10-25 19:28:514718 // The delegate info should only have been logged on header complete. Other
4719 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:484720 log_position =
4721 ExpectLogContainsSomewhereAfter(entries,
4722 log_position + 1,
4723 NetLog::TYPE_URL_REQUEST_DELEGATE,
4724 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:514725
4726 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4727 log_position + 1);
4728
4729 ASSERT_LT(log_position, entries.size());
4730 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4731 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4732
4733 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4734 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4735 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4736 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4737}
4738
4739// Tests handling of delegate info from a URLRequest::Delegate in the case of
4740// an HTTP redirect.
4741TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4742 ASSERT_TRUE(test_server_.Start());
4743
4744 AsyncLoggingUrlRequestDelegate request_delegate(
4745 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4746 TestURLRequestContext context(true);
4747 context.set_network_delegate(NULL);
4748 context.set_net_log(&net_log_);
4749 context.Init();
4750
4751 {
[email protected]f7022f32014-08-21 16:32:194752 scoped_ptr<URLRequest> r(context.CreateRequest(
4753 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364754 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194755 LoadStateWithParam load_state = r->GetLoadState();
4756 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514757 base::RunLoop().Run();
4758
[email protected]f7022f32014-08-21 16:32:194759 EXPECT_EQ(200, r->GetResponseCode());
4760 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514761 }
4762
mmenke43758e62015-05-04 21:09:464763 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514764 net_log_.GetEntries(&entries);
4765
4766 // Delegate info should only have been logged in OnReceivedRedirect and
4767 // OnResponseStarted.
4768 size_t log_position = 0;
4769 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484770 if (i == 0) {
4771 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4772 entries, log_position) + 1;
4773 }
4774
[email protected]abe1c4a2013-10-25 19:28:514775 log_position = ExpectLogContainsSomewhereAfter(
4776 entries,
4777 log_position,
4778 NetLog::TYPE_URL_REQUEST_DELEGATE,
4779 NetLog::PHASE_BEGIN);
4780
4781 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4782 log_position + 1);
4783
4784 ASSERT_LT(log_position, entries.size());
4785 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4786 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4787 }
4788
4789 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4790 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4791 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4792 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4793}
4794
4795// Tests handling of delegate info from a URLRequest::Delegate in the case of
4796// an HTTP redirect, with cancellation at various points.
4797TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4798 ASSERT_TRUE(test_server_.Start());
4799
4800 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4801 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4802 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4803 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4804 };
4805
4806 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4807 ++test_case) {
4808 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4809 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:514810 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:514811 context.set_network_delegate(NULL);
4812 context.set_net_log(&net_log);
4813 context.Init();
4814
4815 {
[email protected]f7022f32014-08-21 16:32:194816 scoped_ptr<URLRequest> r(context.CreateRequest(
4817 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364818 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194819 LoadStateWithParam load_state = r->GetLoadState();
4820 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514821 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194822 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514823 }
4824
mmenke43758e62015-05-04 21:09:464825 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514826 net_log.GetEntries(&entries);
4827
4828 // Delegate info is always logged in both OnReceivedRedirect and
4829 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4830 // OnResponseStarted delegate call is after cancellation, but logging is
4831 // still currently supported in that call.
4832 size_t log_position = 0;
4833 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484834 if (i == 0) {
4835 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4836 entries, log_position) + 1;
4837 }
4838
[email protected]abe1c4a2013-10-25 19:28:514839 log_position = ExpectLogContainsSomewhereAfter(
4840 entries,
4841 log_position,
4842 NetLog::TYPE_URL_REQUEST_DELEGATE,
4843 NetLog::PHASE_BEGIN);
4844
4845 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4846 log_position + 1);
4847
4848 ASSERT_LT(log_position, entries.size());
4849 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4850 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4851 }
4852
4853 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4854 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4855 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4856 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4857 }
4858}
4859
[email protected]847c0fa92012-11-06 16:37:424860namespace {
4861
4862const char kExtraHeader[] = "Allow-Snafu";
4863const char kExtraValue[] = "fubar";
4864
4865class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204866 void OnReceivedRedirect(URLRequest* request,
4867 const RedirectInfo& redirect_info,
4868 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594869 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:424870 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4871 }
4872};
4873
4874} // namespace
4875
4876TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4877 ASSERT_TRUE(test_server_.Start());
4878
4879 GURL destination_url = test_server_.GetURL(
4880 "echoheader?" + std::string(kExtraHeader));
4881 GURL original_url = test_server_.GetURL(
4882 "server-redirect?" + destination_url.spec());
4883 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:364884 scoped_ptr<URLRequest> req(
4885 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194886 req->Start();
[email protected]255620da2013-08-19 13:14:294887 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:424888
4889 std::string value;
[email protected]f7022f32014-08-21 16:32:194890 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:424891 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4892 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:194893 EXPECT_FALSE(req->is_pending());
4894 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:424895 EXPECT_EQ(kExtraValue, d.data_received());
4896}
4897
[email protected]251a1b92012-11-13 11:01:094898namespace {
4899
4900const char kExtraHeaderToRemove[] = "To-Be-Removed";
4901
4902class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204903 void OnReceivedRedirect(URLRequest* request,
4904 const RedirectInfo& redirect_info,
4905 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594906 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:094907 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4908 }
4909};
4910
4911} // namespace
4912
4913TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4914 ASSERT_TRUE(test_server_.Start());
4915
4916 GURL destination_url = test_server_.GetURL(
4917 "echoheader?" + std::string(kExtraHeaderToRemove));
4918 GURL original_url = test_server_.GetURL(
4919 "server-redirect?" + destination_url.spec());
4920 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:364921 scoped_ptr<URLRequest> req(
4922 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194923 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4924 req->Start();
[email protected]255620da2013-08-19 13:14:294925 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:094926
4927 std::string value;
[email protected]f7022f32014-08-21 16:32:194928 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:094929 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:194930 EXPECT_FALSE(req->is_pending());
4931 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:094932 EXPECT_EQ("None", d.data_received());
4933}
4934
[email protected]316c1e5e2012-09-12 15:17:444935TEST_F(URLRequestTestHTTP, CancelTest) {
4936 TestDelegate d;
4937 {
[email protected]f7022f32014-08-21 16:32:194938 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364939 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:444940
[email protected]f7022f32014-08-21 16:32:194941 r->Start();
4942 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444943
[email protected]f7022f32014-08-21 16:32:194944 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:444945
[email protected]255620da2013-08-19 13:14:294946 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444947
4948 // We expect to receive OnResponseStarted even though the request has been
4949 // cancelled.
4950 EXPECT_EQ(1, d.response_started_count());
4951 EXPECT_EQ(0, d.bytes_received());
4952 EXPECT_FALSE(d.received_data_before_response());
4953 }
4954}
4955
4956TEST_F(URLRequestTestHTTP, CancelTest2) {
4957 ASSERT_TRUE(test_server_.Start());
4958
4959 TestDelegate d;
4960 {
[email protected]f7022f32014-08-21 16:32:194961 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364962 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:444963
4964 d.set_cancel_in_response_started(true);
4965
[email protected]f7022f32014-08-21 16:32:194966 r->Start();
4967 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444968
[email protected]255620da2013-08-19 13:14:294969 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444970
4971 EXPECT_EQ(1, d.response_started_count());
4972 EXPECT_EQ(0, d.bytes_received());
4973 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:194974 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:444975 }
4976}
4977
4978TEST_F(URLRequestTestHTTP, CancelTest3) {
4979 ASSERT_TRUE(test_server_.Start());
4980
4981 TestDelegate d;
4982 {
[email protected]f7022f32014-08-21 16:32:194983 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364984 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:444985
4986 d.set_cancel_in_received_data(true);
4987
[email protected]f7022f32014-08-21 16:32:194988 r->Start();
4989 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444990
[email protected]255620da2013-08-19 13:14:294991 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444992
4993 EXPECT_EQ(1, d.response_started_count());
4994 // There is no guarantee about how much data was received
4995 // before the cancel was issued. It could have been 0 bytes,
4996 // or it could have been all the bytes.
4997 // EXPECT_EQ(0, d.bytes_received());
4998 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:194999 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445000 }
5001}
5002
5003TEST_F(URLRequestTestHTTP, CancelTest4) {
5004 ASSERT_TRUE(test_server_.Start());
5005
5006 TestDelegate d;
5007 {
[email protected]f7022f32014-08-21 16:32:195008 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365009 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445010
[email protected]f7022f32014-08-21 16:32:195011 r->Start();
5012 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445013
5014 // The request will be implicitly canceled when it is destroyed. The
5015 // test delegate must not post a quit message when this happens because
5016 // this test doesn't actually have a message loop. The quit message would
5017 // get put on this thread's message queue and the next test would exit
5018 // early, causing problems.
5019 d.set_quit_on_complete(false);
5020 }
5021 // expect things to just cleanup properly.
5022
5023 // we won't actually get a received reponse here because we've never run the
5024 // message loop
5025 EXPECT_FALSE(d.received_data_before_response());
5026 EXPECT_EQ(0, d.bytes_received());
5027}
5028
5029TEST_F(URLRequestTestHTTP, CancelTest5) {
5030 ASSERT_TRUE(test_server_.Start());
5031
5032 // populate cache
5033 {
5034 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195035 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365036 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195037 r->Start();
[email protected]255620da2013-08-19 13:14:295038 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195039 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445040 }
5041
5042 // cancel read from cache (see bug 990242)
5043 {
5044 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195045 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365046 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195047 r->Start();
5048 r->Cancel();
[email protected]255620da2013-08-19 13:14:295049 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445050
[email protected]f7022f32014-08-21 16:32:195051 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445052 EXPECT_EQ(1, d.response_started_count());
5053 EXPECT_EQ(0, d.bytes_received());
5054 EXPECT_FALSE(d.received_data_before_response());
5055 }
5056}
5057
5058TEST_F(URLRequestTestHTTP, PostTest) {
5059 ASSERT_TRUE(test_server_.Start());
5060 HTTPUploadDataOperationTest("POST");
5061}
5062
5063TEST_F(URLRequestTestHTTP, PutTest) {
5064 ASSERT_TRUE(test_server_.Start());
5065 HTTPUploadDataOperationTest("PUT");
5066}
5067
5068TEST_F(URLRequestTestHTTP, PostEmptyTest) {
5069 ASSERT_TRUE(test_server_.Start());
5070
5071 TestDelegate d;
5072 {
[email protected]f7022f32014-08-21 16:32:195073 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365074 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195075 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445076
[email protected]f7022f32014-08-21 16:32:195077 r->Start();
5078 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445079
[email protected]255620da2013-08-19 13:14:295080 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445081
[email protected]329b68b2012-11-14 17:54:275082 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195083 << "request failed: " << r->status().status()
5084 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445085
5086 EXPECT_FALSE(d.received_data_before_response());
5087 EXPECT_TRUE(d.data_received().empty());
5088 }
5089}
5090
5091TEST_F(URLRequestTestHTTP, PostFileTest) {
5092 ASSERT_TRUE(test_server_.Start());
5093
5094 TestDelegate d;
5095 {
[email protected]f7022f32014-08-21 16:32:195096 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365097 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195098 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445099
[email protected]6cdfd7f2013-02-08 20:40:155100 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445101 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025102 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445103
[email protected]f288ef02012-12-15 20:28:285104 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445105
[email protected]6cdfd7f2013-02-08 20:40:155106 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445107 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5108 path = path.Append(FILE_PATH_LITERAL("net"));
5109 path = path.Append(FILE_PATH_LITERAL("data"));
5110 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5111 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:365112 element_readers.push_back(
5113 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
5114 path,
5115 0,
5116 kuint64max,
5117 base::Time()));
mmenkecbc2b712014-10-09 20:29:075118 r->set_upload(make_scoped_ptr<UploadDataStream>(
5119 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:445120
[email protected]f7022f32014-08-21 16:32:195121 r->Start();
5122 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445123
[email protected]255620da2013-08-19 13:14:295124 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445125
pkasting6b68a162014-12-01 22:10:295126 int64 size64 = 0;
5127 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5128 ASSERT_LE(size64, std::numeric_limits<int>::max());
5129 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175130 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445131
[email protected]7600d0b2013-12-08 21:43:305132 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445133
[email protected]329b68b2012-11-14 17:54:275134 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195135 << "request failed: " << r->status().status()
5136 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445137
5138 EXPECT_FALSE(d.received_data_before_response());
5139
[email protected]329b68b2012-11-14 17:54:275140 EXPECT_EQ(size, d.bytes_received());
5141 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445142 }
5143}
5144
[email protected]999dd8c2013-11-12 06:45:545145TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
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]999dd8c2013-11-12 06:45:545153
5154 ScopedVector<UploadElementReader> element_readers;
5155
5156 element_readers.push_back(new UploadFileElementReader(
5157 base::MessageLoopProxy::current().get(),
5158 base::FilePath(FILE_PATH_LITERAL(
5159 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
5160 0,
5161 kuint64max,
5162 base::Time()));
mmenkecbc2b712014-10-09 20:29:075163 r->set_upload(make_scoped_ptr<UploadDataStream>(
5164 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]999dd8c2013-11-12 06:45:545165
[email protected]f7022f32014-08-21 16:32:195166 r->Start();
5167 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545168
5169 base::RunLoop().Run();
5170
[email protected]999dd8c2013-11-12 06:45:545171 EXPECT_TRUE(d.request_failed());
5172 EXPECT_FALSE(d.received_data_before_response());
5173 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195174 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5175 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545176 }
5177}
5178
[email protected]316c1e5e2012-09-12 15:17:445179TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5180 ASSERT_TRUE(test_server_.Start());
5181
5182 TestDelegate d;
5183 {
[email protected]f7022f32014-08-21 16:32:195184 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365185 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195186 r->EnableChunkedUpload();
5187 r->set_method("POST");
5188 AddChunksToUpload(r.get());
5189 r->Start();
5190 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445191
[email protected]255620da2013-08-19 13:14:295192 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445193
[email protected]f7022f32014-08-21 16:32:195194 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445195 }
5196}
5197
[email protected]329b68b2012-11-14 17:54:275198TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5199 ASSERT_TRUE(test_server_.Start());
5200
5201 TestDelegate d;
5202 {
[email protected]f7022f32014-08-21 16:32:195203 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365204 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195205 r->EnableChunkedUpload();
5206 r->set_method("POST");
5207 r->Start();
5208 EXPECT_TRUE(r->is_pending());
5209 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295210 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275211
[email protected]f7022f32014-08-21 16:32:195212 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275213 }
5214}
5215
[email protected]316c1e5e2012-09-12 15:17:445216TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5217 ASSERT_TRUE(test_server_.Start());
5218
5219 TestDelegate d;
5220 {
[email protected]f7022f32014-08-21 16:32:195221 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365222 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195223 r->EnableChunkedUpload();
5224 r->set_method("POST");
5225 r->Start();
5226 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445227
[email protected]255620da2013-08-19 13:14:295228 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195229 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295230 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445231
[email protected]f7022f32014-08-21 16:32:195232 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445233 }
5234}
5235
5236TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5237 ASSERT_TRUE(test_server_.Start());
5238
5239 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195240 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365241 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195242 req->Start();
[email protected]255620da2013-08-19 13:14:295243 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445244
[email protected]f7022f32014-08-21 16:32:195245 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445246
5247 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195248 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445249
5250 std::string header;
5251 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5252 EXPECT_EQ("private", header);
5253
5254 header.clear();
5255 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5256 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5257
5258 // The response has two "X-Multiple-Entries" headers.
5259 // This verfies our output has them concatenated together.
5260 header.clear();
5261 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5262 EXPECT_EQ("a, b", header);
5263}
5264
[email protected]242d8562012-10-30 21:20:465265TEST_F(URLRequestTestHTTP, ProcessSTS) {
estarka5da76702015-04-09 04:00:165266 SpawnedTestServer::SSLOptions ssl_options(
5267 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
[email protected]ce7d0cbc2013-05-03 18:57:225268 SpawnedTestServer https_test_server(
5269 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465270 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155271 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465272 ASSERT_TRUE(https_test_server.Start());
5273
estarka5da76702015-04-09 04:00:165274 std::string test_server_hostname = https_test_server.GetURL("").host();
5275
[email protected]242d8562012-10-30 21:20:465276 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195277 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365278 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5279 &d));
[email protected]f7022f32014-08-21 16:32:195280 request->Start();
[email protected]255620da2013-08-19 13:14:295281 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465282
5283 TransportSecurityState* security_state =
5284 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465285 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165286 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5287 &domain_state));
[email protected]242d8562012-10-30 21:20:465288 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265289 domain_state.sts.upgrade_mode);
5290 EXPECT_TRUE(domain_state.sts.include_subdomains);
5291 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275292#if defined(OS_ANDROID)
5293 // Android's CertVerifyProc does not (yet) handle pins.
5294#else
5295 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5296#endif
5297}
5298
estarka5da76702015-04-09 04:00:165299TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
5300 SpawnedTestServer https_test_server(
5301 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::SSLOptions(),
5302 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5303 ASSERT_TRUE(https_test_server.Start());
5304 // Make sure this test fails if the test server is changed to not
5305 // listen on an IP by default.
5306 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5307 std::string test_server_hostname = https_test_server.GetURL("").host();
5308
5309 TestDelegate d;
5310 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5311 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5312 &d));
5313 request->Start();
5314 base::RunLoop().Run();
5315
5316 TransportSecurityState* security_state =
5317 default_context_.transport_security_state();
5318 TransportSecurityState::DomainState domain_state;
5319 EXPECT_FALSE(security_state->GetDynamicDomainState(test_server_hostname,
5320 &domain_state));
5321}
5322
[email protected]37fd55fb2013-06-29 13:13:275323// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5324// reject HPKP headers, and a test setting only HPKP headers will fail (no
5325// DomainState present because header rejected).
5326#if defined(OS_ANDROID)
5327#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5328#else
5329#define MAYBE_ProcessPKP ProcessPKP
5330#endif
5331
5332// Tests that enabling HPKP on a domain does not affect the HSTS
5333// validity/expiration.
5334TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estarka5da76702015-04-09 04:00:165335 SpawnedTestServer::SSLOptions ssl_options(
5336 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
[email protected]37fd55fb2013-06-29 13:13:275337 SpawnedTestServer https_test_server(
5338 SpawnedTestServer::TYPE_HTTPS,
5339 ssl_options,
5340 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5341 ASSERT_TRUE(https_test_server.Start());
5342
estarka5da76702015-04-09 04:00:165343 std::string test_server_hostname = https_test_server.GetURL("").host();
5344
[email protected]37fd55fb2013-06-29 13:13:275345 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195346 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365347 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5348 &d));
[email protected]f7022f32014-08-21 16:32:195349 request->Start();
[email protected]255620da2013-08-19 13:14:295350 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275351
5352 TransportSecurityState* security_state =
5353 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275354 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165355 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5356 &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275357 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
[email protected]9e6968d2014-05-07 21:46:265358 domain_state.sts.upgrade_mode);
5359 EXPECT_FALSE(domain_state.sts.include_subdomains);
5360 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275361 EXPECT_TRUE(domain_state.HasPublicKeyPins());
[email protected]9e6968d2014-05-07 21:46:265362 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]242d8562012-10-30 21:20:465363}
5364
estarka5da76702015-04-09 04:00:165365TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
5366 SpawnedTestServer https_test_server(
5367 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::SSLOptions(),
5368 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5369 ASSERT_TRUE(https_test_server.Start());
5370 // Make sure this test fails if the test server is changed to not
5371 // listen on an IP by default.
5372 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5373 std::string test_server_hostname = https_test_server.GetURL("").host();
5374
5375 TestDelegate d;
5376 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5377 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5378 &d));
5379 request->Start();
5380 base::RunLoop().Run();
5381
5382 TransportSecurityState* security_state =
5383 default_context_.transport_security_state();
5384 TransportSecurityState::DomainState domain_state;
5385 EXPECT_FALSE(security_state->GetDynamicDomainState(test_server_hostname,
5386 &domain_state));
5387}
5388
[email protected]242d8562012-10-30 21:20:465389TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
estarka5da76702015-04-09 04:00:165390 SpawnedTestServer::SSLOptions ssl_options(
5391 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
[email protected]ce7d0cbc2013-05-03 18:57:225392 SpawnedTestServer https_test_server(
5393 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465394 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155395 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465396 ASSERT_TRUE(https_test_server.Start());
5397
estarka5da76702015-04-09 04:00:165398 std::string test_server_hostname = https_test_server.GetURL("").host();
5399
[email protected]242d8562012-10-30 21:20:465400 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195401 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]242d8562012-10-30 21:20:465402 https_test_server.GetURL("files/hsts-multiple-headers.html"),
davidben151423e2015-03-23 18:48:365403 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195404 request->Start();
[email protected]255620da2013-08-19 13:14:295405 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465406
5407 // We should have set parameters from the first header, not the second.
5408 TransportSecurityState* security_state =
5409 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465410 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165411 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5412 &domain_state));
[email protected]242d8562012-10-30 21:20:465413 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265414 domain_state.sts.upgrade_mode);
5415 EXPECT_FALSE(domain_state.sts.include_subdomains);
5416 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]242d8562012-10-30 21:20:465417}
5418
[email protected]9f972ec2013-04-10 20:24:365419TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
estarka5da76702015-04-09 04:00:165420 SpawnedTestServer::SSLOptions ssl_options(
5421 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
[email protected]ce7d0cbc2013-05-03 18:57:225422 SpawnedTestServer https_test_server(
5423 SpawnedTestServer::TYPE_HTTPS,
[email protected]9f972ec2013-04-10 20:24:365424 ssl_options,
5425 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5426 ASSERT_TRUE(https_test_server.Start());
5427
estarka5da76702015-04-09 04:00:165428 std::string test_server_hostname = https_test_server.GetURL("").host();
5429
[email protected]9f972ec2013-04-10 20:24:365430 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195431 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]9f972ec2013-04-10 20:24:365432 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
davidben151423e2015-03-23 18:48:365433 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195434 request->Start();
[email protected]255620da2013-08-19 13:14:295435 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365436
5437 // We should have set parameters from the first header, not the second.
5438 TransportSecurityState* security_state =
5439 default_context_.transport_security_state();
[email protected]9f972ec2013-04-10 20:24:365440 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165441 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5442 &domain_state));
[email protected]9f972ec2013-04-10 20:24:365443 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265444 domain_state.sts.upgrade_mode);
[email protected]9f972ec2013-04-10 20:24:365445#if defined(OS_ANDROID)
5446 // Android's CertVerifyProc does not (yet) handle pins.
5447#else
5448 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5449#endif
[email protected]9e6968d2014-05-07 21:46:265450 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]9f972ec2013-04-10 20:24:365451
[email protected]a165f092013-06-12 16:10:055452 // Even though there is an HSTS header asserting includeSubdomains, it is
5453 // the *second* such header, and we MUST process only the first.
[email protected]9e6968d2014-05-07 21:46:265454 EXPECT_FALSE(domain_state.sts.include_subdomains);
[email protected]a165f092013-06-12 16:10:055455 // includeSubdomains does not occur in the test HPKP header.
[email protected]9e6968d2014-05-07 21:46:265456 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365457}
5458
[email protected]37fd55fb2013-06-29 13:13:275459// Tests that when multiple HPKP headers are present, asserting different
5460// policies, that only the first such policy is processed.
5461TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
estarka5da76702015-04-09 04:00:165462 SpawnedTestServer::SSLOptions ssl_options(
5463 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
[email protected]37fd55fb2013-06-29 13:13:275464 SpawnedTestServer https_test_server(
5465 SpawnedTestServer::TYPE_HTTPS,
5466 ssl_options,
5467 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5468 ASSERT_TRUE(https_test_server.Start());
5469
estarka5da76702015-04-09 04:00:165470 std::string test_server_hostname = https_test_server.GetURL("").host();
5471
[email protected]37fd55fb2013-06-29 13:13:275472 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195473 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]37fd55fb2013-06-29 13:13:275474 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:365475 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195476 request->Start();
[email protected]255620da2013-08-19 13:14:295477 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275478
5479 TransportSecurityState* security_state =
5480 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275481 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165482 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5483 &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275484 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265485 domain_state.sts.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:275486#if defined(OS_ANDROID)
5487 // Android's CertVerifyProc does not (yet) handle pins.
5488#else
5489 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5490#endif
[email protected]9e6968d2014-05-07 21:46:265491 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]37fd55fb2013-06-29 13:13:275492
[email protected]9e6968d2014-05-07 21:46:265493 EXPECT_TRUE(domain_state.sts.include_subdomains);
5494 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275495}
5496
[email protected]316c1e5e2012-09-12 15:17:445497TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5498 ASSERT_TRUE(test_server_.Start());
5499
5500 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195501 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5502 test_server_.GetURL("files/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:365503 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195504 req->Start();
[email protected]255620da2013-08-19 13:14:295505 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445506
5507 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:195508 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:445509 EXPECT_EQ("text/html", mime_type);
5510
5511 std::string charset;
[email protected]f7022f32014-08-21 16:32:195512 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:445513 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:195514 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445515}
5516
[email protected]02494ec2014-05-07 15:05:295517TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:345518 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:345519 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:345520 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025521 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345522
5523 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505524 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345525}
5526
[email protected]02494ec2014-05-07 15:05:295527#if !defined(DISABLE_FILE_SUPPORT)
5528TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5529 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5530 GURL file_url("file:///foo.txt");
5531 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5532 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5533
5534 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505535 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:295536}
5537
[email protected]588614c22013-08-16 00:09:025538TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445539 ASSERT_TRUE(test_server_.Start());
5540
5541 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195542 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365543 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY,
5544 &d));
[email protected]f7022f32014-08-21 16:32:195545 req->Start();
[email protected]255620da2013-08-19 13:14:295546 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445547
[email protected]f7022f32014-08-21 16:32:195548 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5549 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445550}
[email protected]02494ec2014-05-07 15:05:295551#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:445552
[email protected]588614c22013-08-16 00:09:025553TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5554 ASSERT_TRUE(test_server_.Start());
5555
5556 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195557 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365558 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY,
5559 &d));
[email protected]f7022f32014-08-21 16:32:195560 req->Start();
[email protected]588614c22013-08-16 00:09:025561 base::MessageLoop::current()->Run();
5562
[email protected]f7022f32014-08-21 16:32:195563 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5564 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:025565}
5566
[email protected]316c1e5e2012-09-12 15:17:445567TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5568 ASSERT_TRUE(test_server_.Start());
5569
5570 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195571 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5572 test_server_.GetURL("files/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:365573 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195574 req->Start();
[email protected]255620da2013-08-19 13:14:295575 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445576
[email protected]f7022f32014-08-21 16:32:195577 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5578 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445579}
5580
[email protected]e50efea2014-03-24 18:41:005581// Make sure redirects are cached, despite not reading their bodies.
5582TEST_F(URLRequestTestHTTP, CacheRedirect) {
5583 ASSERT_TRUE(test_server_.Start());
5584 GURL redirect_url =
5585 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5586
5587 {
5588 TestDelegate d;
davidben151423e2015-03-23 18:48:365589 scoped_ptr<URLRequest> req(
5590 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195591 req->Start();
[email protected]e50efea2014-03-24 18:41:005592 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195593 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005594 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195595 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005596 }
5597
5598 {
5599 TestDelegate d;
5600 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:365601 scoped_ptr<URLRequest> req(
5602 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195603 req->Start();
[email protected]e50efea2014-03-24 18:41:005604 base::RunLoop().Run();
5605
5606 EXPECT_EQ(1, d.received_redirect_count());
5607 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195608 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005609
[email protected]f7022f32014-08-21 16:32:195610 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:005611 base::RunLoop().Run();
5612 EXPECT_EQ(1, d.received_redirect_count());
5613 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195614 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5615 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005616 }
5617}
5618
5619// Make sure a request isn't cached when a NetworkDelegate forces a redirect
5620// when the headers are read, since the body won't have been read.
5621TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5622 ASSERT_TRUE(test_server_.Start());
5623 // URL that is normally cached.
5624 GURL initial_url = test_server_.GetURL("cachetime");
5625
5626 {
5627 // Set up the TestNetworkDelegate tp force a redirect.
5628 GURL redirect_to_url = test_server_.GetURL("echo");
5629 default_network_delegate_.set_redirect_on_headers_received_url(
5630 redirect_to_url);
5631
5632 TestDelegate d;
davidben151423e2015-03-23 18:48:365633 scoped_ptr<URLRequest> req(
5634 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195635 req->Start();
[email protected]e50efea2014-03-24 18:41:005636 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195637 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005638 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195639 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:005640 }
5641
5642 {
5643 TestDelegate d;
davidben151423e2015-03-23 18:48:365644 scoped_ptr<URLRequest> req(
5645 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195646 req->Start();
[email protected]e50efea2014-03-24 18:41:005647 base::RunLoop().Run();
5648
[email protected]f7022f32014-08-21 16:32:195649 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5650 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005651 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195652 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:005653 }
5654}
5655
[email protected]5f714132014-03-26 10:41:165656// Tests that redirection to an unsafe URL is allowed when it has been marked as
5657// safe.
5658TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5659 ASSERT_TRUE(test_server_.Start());
5660
5661 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5662 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5663 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5664
5665 TestDelegate d;
5666 {
[email protected]f7022f32014-08-21 16:32:195667 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365668 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165669
[email protected]f7022f32014-08-21 16:32:195670 r->Start();
[email protected]5f714132014-03-26 10:41:165671 base::RunLoop().Run();
5672
[email protected]f7022f32014-08-21 16:32:195673 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:165674
[email protected]f7022f32014-08-21 16:32:195675 EXPECT_EQ(2U, r->url_chain().size());
5676 EXPECT_EQ(OK, r->status().error());
5677 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:165678 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5679 }
5680}
5681
5682// Tests that a redirect to a different unsafe URL is blocked, even after adding
5683// some other URL to the whitelist.
5684TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5685 ASSERT_TRUE(test_server_.Start());
5686
5687 GURL unsafe_url("data:text/html,something");
5688 GURL different_unsafe_url("data:text/html,something-else");
5689 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5690 default_network_delegate_.set_allowed_unsafe_redirect_url(
5691 different_unsafe_url);
5692
5693 TestDelegate d;
5694 {
[email protected]f7022f32014-08-21 16:32:195695 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365696 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165697
[email protected]f7022f32014-08-21 16:32:195698 r->Start();
[email protected]5f714132014-03-26 10:41:165699 base::RunLoop().Run();
5700
[email protected]f7022f32014-08-21 16:32:195701 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5702 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:165703 }
5704}
5705
[email protected]5f714132014-03-26 10:41:165706// Redirects from an URL with fragment to an unsafe URL with fragment should
5707// be allowed, and the reference fragment of the target URL should be preserved.
5708TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5709 ASSERT_TRUE(test_server_.Start());
5710
5711 GURL original_url(test_server_.GetURL("original#fragment1"));
5712 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5713 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5714
5715 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5716 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5717
5718 TestDelegate d;
5719 {
davidben151423e2015-03-23 18:48:365720 scoped_ptr<URLRequest> r(
5721 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165722
[email protected]f7022f32014-08-21 16:32:195723 r->Start();
[email protected]5f714132014-03-26 10:41:165724 base::RunLoop().Run();
5725
[email protected]f7022f32014-08-21 16:32:195726 EXPECT_EQ(2U, r->url_chain().size());
5727 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5728 EXPECT_EQ(OK, r->status().error());
5729 EXPECT_EQ(original_url, r->original_url());
5730 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:165731 }
5732}
5733
5734// When a delegate has specified a safe redirect URL, but it does not match the
5735// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:145736TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:165737 ASSERT_TRUE(test_server_.Start());
5738
5739 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5740 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5741 GURL redirect_url(test_server_.GetURL("target"));
5742 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5743
5744 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5745 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5746
5747 TestDelegate d;
5748 {
davidben151423e2015-03-23 18:48:365749 scoped_ptr<URLRequest> r(
5750 default_context_.CreateRequest(original_url, 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(2U, r->url_chain().size());
5756 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5757 EXPECT_EQ(OK, r->status().error());
5758 EXPECT_EQ(original_url, r->original_url());
5759 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:165760 }
5761}
5762
[email protected]f878230e2014-04-03 15:36:145763// When a delegate has specified a safe redirect URL, assume that the redirect
5764// URL should not be changed. In particular, the reference fragment should not
5765// be modified.
5766TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5767 ASSERT_TRUE(test_server_.Start());
5768
5769 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5770 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5771
5772 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5773 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5774
5775 TestDelegate d;
5776 {
davidben151423e2015-03-23 18:48:365777 scoped_ptr<URLRequest> r(
5778 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145779
[email protected]f7022f32014-08-21 16:32:195780 r->Start();
[email protected]f878230e2014-04-03 15:36:145781 base::RunLoop().Run();
5782
[email protected]f7022f32014-08-21 16:32:195783 EXPECT_EQ(2U, r->url_chain().size());
5784 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5785 EXPECT_EQ(OK, r->status().error());
5786 EXPECT_EQ(original_url, r->original_url());
5787 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145788 }
5789}
5790
5791// When a URLRequestRedirectJob is created, the redirection must be followed and
5792// the reference fragment of the target URL must not be modified.
5793TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5794 ASSERT_TRUE(test_server_.Start());
5795
5796 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5797 GURL redirect_url(test_server_.GetURL("echo"));
5798
5799 TestDelegate d;
davidben151423e2015-03-23 18:48:365800 scoped_ptr<URLRequest> r(
5801 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145802
5803 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:195804 r.get(), &default_network_delegate_, redirect_url,
[email protected]f878230e2014-04-03 15:36:145805 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5806 AddTestInterceptor()->set_main_intercept_job(job);
5807
[email protected]f7022f32014-08-21 16:32:195808 r->Start();
[email protected]f878230e2014-04-03 15:36:145809 base::RunLoop().Run();
5810
[email protected]f7022f32014-08-21 16:32:195811 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5812 EXPECT_EQ(OK, r->status().error());
5813 EXPECT_EQ(original_url, r->original_url());
5814 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145815}
5816
[email protected]316c1e5e2012-09-12 15:17:445817TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5818 ASSERT_TRUE(test_server_.Start());
5819
5820 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195821 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365822 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195823 req->SetReferrer("http://user:[email protected]/");
5824 req->Start();
[email protected]255620da2013-08-19 13:14:295825 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445826
5827 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5828}
5829
[email protected]99ecf6e2013-04-10 22:46:135830TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5831 ASSERT_TRUE(test_server_.Start());
5832
5833 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195834 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365835 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195836 req->SetReferrer("http://foo.com/test#fragment");
5837 req->Start();
[email protected]255620da2013-08-19 13:14:295838 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135839
5840 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5841}
5842
5843TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5844 ASSERT_TRUE(test_server_.Start());
5845
5846 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195847 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365848 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195849 req->SetReferrer("http://foo.com/test#fragment");
5850 req->SetReferrer("");
5851 req->Start();
[email protected]255620da2013-08-19 13:14:295852 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135853
5854 EXPECT_EQ(std::string("None"), d.data_received());
5855}
5856
[email protected]1826a402014-01-08 15:40:485857// Defer network start and then resume, checking that the request was a success
5858// and bytes were received.
5859TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5860 ASSERT_TRUE(test_server_.Start());
5861
5862 TestDelegate d;
5863 {
5864 d.set_quit_on_network_start(true);
5865 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365866 scoped_ptr<URLRequest> req(
5867 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485868
[email protected]f7022f32014-08-21 16:32:195869 req->Start();
[email protected]1826a402014-01-08 15:40:485870 base::RunLoop().Run();
5871
5872 EXPECT_EQ(1, d.received_before_network_start_count());
5873 EXPECT_EQ(0, d.response_started_count());
5874
[email protected]f7022f32014-08-21 16:32:195875 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485876 base::RunLoop().Run();
5877
5878 EXPECT_EQ(1, d.response_started_count());
5879 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195880 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485881 }
5882}
5883
5884// Check that OnBeforeNetworkStart is only called once even if there is a
5885// redirect.
5886TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5887 ASSERT_TRUE(test_server_.Start());
5888
5889 TestDelegate d;
5890 {
5891 d.set_quit_on_redirect(true);
5892 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:195893 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365894 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485895
[email protected]f7022f32014-08-21 16:32:195896 req->Start();
[email protected]1826a402014-01-08 15:40:485897 base::RunLoop().Run();
5898
5899 EXPECT_EQ(1, d.received_before_network_start_count());
5900 EXPECT_EQ(0, d.response_started_count());
5901 EXPECT_EQ(0, d.received_redirect_count());
5902
[email protected]f7022f32014-08-21 16:32:195903 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485904 base::RunLoop().Run();
5905
5906 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195907 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:485908 base::RunLoop().Run();
5909
5910 // Check that the redirect's new network transaction does not get propagated
5911 // to a second OnBeforeNetworkStart() notification.
5912 EXPECT_EQ(1, d.received_before_network_start_count());
5913
5914 EXPECT_EQ(1, d.response_started_count());
5915 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195916 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485917 }
5918}
5919
5920// Cancel the request after learning that the request would use the network.
5921TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5922 ASSERT_TRUE(test_server_.Start());
5923
5924 TestDelegate d;
5925 {
5926 d.set_quit_on_network_start(true);
5927 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365928 scoped_ptr<URLRequest> req(
5929 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485930
[email protected]f7022f32014-08-21 16:32:195931 req->Start();
[email protected]1826a402014-01-08 15:40:485932 base::RunLoop().Run();
5933
5934 EXPECT_EQ(1, d.received_before_network_start_count());
5935 EXPECT_EQ(0, d.response_started_count());
5936
[email protected]f7022f32014-08-21 16:32:195937 req->Cancel();
[email protected]1826a402014-01-08 15:40:485938 base::RunLoop().Run();
5939
5940 EXPECT_EQ(1, d.response_started_count());
5941 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195942 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:485943 }
5944}
5945
[email protected]316c1e5e2012-09-12 15:17:445946TEST_F(URLRequestTestHTTP, CancelRedirect) {
5947 ASSERT_TRUE(test_server_.Start());
5948
5949 TestDelegate d;
5950 {
5951 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:195952 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365953 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195954 req->Start();
[email protected]255620da2013-08-19 13:14:295955 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445956
5957 EXPECT_EQ(1, d.response_started_count());
5958 EXPECT_EQ(0, d.bytes_received());
5959 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195960 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:445961 }
5962}
5963
5964TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5965 ASSERT_TRUE(test_server_.Start());
5966
5967 TestDelegate d;
5968 {
5969 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:045970 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:365971 scoped_ptr<URLRequest> req(
5972 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:045973
[email protected]f7022f32014-08-21 16:32:195974 req->Start();
[email protected]255620da2013-08-19 13:14:295975 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445976
5977 EXPECT_EQ(1, d.received_redirect_count());
5978
[email protected]f7022f32014-08-21 16:32:195979 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:295980 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445981
5982 EXPECT_EQ(1, d.response_started_count());
5983 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195984 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:445985
[email protected]6cdfd7f2013-02-08 20:40:155986 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445987 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5988 path = path.Append(FILE_PATH_LITERAL("net"));
5989 path = path.Append(FILE_PATH_LITERAL("data"));
5990 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5991 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5992
5993 std::string contents;
[email protected]82f84b92013-08-30 18:23:505994 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:445995 EXPECT_EQ(contents, d.data_received());
5996 }
5997}
5998
[email protected]79e1fd62013-06-20 06:50:045999TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
6000 ASSERT_TRUE(test_server_.Start());
6001
6002 TestDelegate d;
6003 {
6004 d.set_quit_on_redirect(true);
6005 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366006 scoped_ptr<URLRequest> req(
6007 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046008
6009 EXPECT_FALSE(d.have_full_request_headers());
6010
[email protected]f7022f32014-08-21 16:32:196011 req->Start();
[email protected]255620da2013-08-19 13:14:296012 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046013
6014 EXPECT_EQ(1, d.received_redirect_count());
6015 EXPECT_TRUE(d.have_full_request_headers());
6016 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6017 d.ClearFullRequestHeaders();
6018
[email protected]f7022f32014-08-21 16:32:196019 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296020 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046021
6022 GURL target_url(test_server_.GetURL("files/with-headers.html"));
6023 EXPECT_EQ(1, d.response_started_count());
6024 EXPECT_TRUE(d.have_full_request_headers());
6025 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6026 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196027 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046028
6029 base::FilePath path;
6030 PathService::Get(base::DIR_SOURCE_ROOT, &path);
6031 path = path.Append(FILE_PATH_LITERAL("net"));
6032 path = path.Append(FILE_PATH_LITERAL("data"));
6033 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
6034 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6035
6036 std::string contents;
[email protected]82f84b92013-08-30 18:23:506037 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046038 EXPECT_EQ(contents, d.data_received());
6039 }
6040}
6041
[email protected]316c1e5e2012-09-12 15:17:446042TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
6043 ASSERT_TRUE(test_server_.Start());
6044
6045 TestDelegate d;
6046 {
6047 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196048 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366049 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196050 req->Start();
[email protected]255620da2013-08-19 13:14:296051 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446052
6053 EXPECT_EQ(1, d.received_redirect_count());
6054
[email protected]f7022f32014-08-21 16:32:196055 req->Cancel();
[email protected]255620da2013-08-19 13:14:296056 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446057
6058 EXPECT_EQ(1, d.response_started_count());
6059 EXPECT_EQ(0, d.bytes_received());
6060 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196061 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446062 }
6063}
6064
6065TEST_F(URLRequestTestHTTP, VaryHeader) {
6066 ASSERT_TRUE(test_server_.Start());
6067
[email protected]3b23a222013-05-15 21:33:256068 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446069 {
6070 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196071 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366072 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446073 HttpRequestHeaders headers;
6074 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196075 req->SetExtraRequestHeaders(headers);
6076 req->Start();
[email protected]255620da2013-08-19 13:14:296077 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256078
6079 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196080 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256081 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446082 }
6083
[email protected]3b23a222013-05-15 21:33:256084 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446085 {
6086 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196087 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366088 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446089 HttpRequestHeaders headers;
6090 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196091 req->SetExtraRequestHeaders(headers);
6092 req->Start();
[email protected]255620da2013-08-19 13:14:296093 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446094
[email protected]f7022f32014-08-21 16:32:196095 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256096
6097 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196098 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256099 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446100 }
6101
[email protected]3b23a222013-05-15 21:33:256102 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446103 {
6104 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196105 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366106 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446107 HttpRequestHeaders headers;
6108 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196109 req->SetExtraRequestHeaders(headers);
6110 req->Start();
[email protected]255620da2013-08-19 13:14:296111 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446112
[email protected]f7022f32014-08-21 16:32:196113 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256114
6115 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196116 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256117 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446118 }
6119}
6120
6121TEST_F(URLRequestTestHTTP, BasicAuth) {
6122 ASSERT_TRUE(test_server_.Start());
6123
6124 // populate the cache
6125 {
6126 TestDelegate d;
6127 d.set_credentials(AuthCredentials(kUser, kSecret));
6128
[email protected]f7022f32014-08-21 16:32:196129 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366130 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196131 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446132
[email protected]255620da2013-08-19 13:14:296133 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446134
6135 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6136 }
6137
6138 // repeat request with end-to-end validation. since auth-basic results in a
6139 // cachable page, we expect this test to result in a 304. in which case, the
6140 // response should be fetched from the cache.
6141 {
6142 TestDelegate d;
6143 d.set_credentials(AuthCredentials(kUser, kSecret));
6144
[email protected]f7022f32014-08-21 16:32:196145 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366146 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196147 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6148 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446149
[email protected]255620da2013-08-19 13:14:296150 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446151
6152 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6153
6154 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196155 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446156 }
6157}
6158
6159// Check that Set-Cookie headers in 401 responses are respected.
6160// http://crbug.com/6450
6161TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6162 ASSERT_TRUE(test_server_.Start());
6163
6164 GURL url_requiring_auth =
6165 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6166
6167 // Request a page that will give a 401 containing a Set-Cookie header.
6168 // Verify that when the transaction is restarted, it includes the new cookie.
6169 {
[email protected]ceefd7fd2012-11-29 00:36:246170 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446171 TestURLRequestContext context(true);
6172 context.set_network_delegate(&network_delegate);
6173 context.Init();
6174
6175 TestDelegate d;
6176 d.set_credentials(AuthCredentials(kUser, kSecret));
6177
davidben151423e2015-03-23 18:48:366178 scoped_ptr<URLRequest> r(
6179 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196180 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446181
[email protected]255620da2013-08-19 13:14:296182 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446183
6184 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6185
6186 // Make sure we sent the cookie in the restarted transaction.
6187 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6188 != std::string::npos);
6189 }
6190
6191 // Same test as above, except this time the restart is initiated earlier
6192 // (without user intervention since identity is embedded in the URL).
6193 {
[email protected]ceefd7fd2012-11-29 00:36:246194 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446195 TestURLRequestContext context(true);
6196 context.set_network_delegate(&network_delegate);
6197 context.Init();
6198
6199 TestDelegate d;
6200
6201 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186202 replacements.SetUsernameStr("user2");
6203 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446204 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6205
davidben151423e2015-03-23 18:48:366206 scoped_ptr<URLRequest> r(
6207 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196208 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446209
[email protected]255620da2013-08-19 13:14:296210 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446211
6212 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6213
6214 // Make sure we sent the cookie in the restarted transaction.
6215 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6216 != std::string::npos);
6217 }
6218}
6219
[email protected]58e32bb2013-01-21 18:23:256220// Tests that load timing works as expected with auth and the cache.
6221TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6222 ASSERT_TRUE(test_server_.Start());
6223
6224 // populate the cache
6225 {
6226 TestDelegate d;
6227 d.set_credentials(AuthCredentials(kUser, kSecret));
6228
[email protected]f7022f32014-08-21 16:32:196229 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366230 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196231 r->Start();
[email protected]58e32bb2013-01-21 18:23:256232
[email protected]255620da2013-08-19 13:14:296233 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256234
6235 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6236
6237 LoadTimingInfo load_timing_info_before_auth;
6238 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6239 &load_timing_info_before_auth));
6240 TestLoadTimingNotReused(load_timing_info_before_auth,
6241 CONNECT_TIMING_HAS_DNS_TIMES);
6242
6243 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196244 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256245 // The test server does not support keep alive sockets, so the second
6246 // request with auth should use a new socket.
6247 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6248 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6249 load_timing_info.socket_log_id);
6250 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6251 load_timing_info.connect_timing.connect_start);
6252 }
6253
[email protected]3b23a222013-05-15 21:33:256254 // Repeat request with end-to-end validation. Since auth-basic results in a
6255 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256256 // response should be fetched from the cache.
6257 {
6258 TestDelegate d;
6259 d.set_credentials(AuthCredentials(kUser, kSecret));
6260
[email protected]f7022f32014-08-21 16:32:196261 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366262 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196263 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6264 r->Start();
[email protected]58e32bb2013-01-21 18:23:256265
[email protected]255620da2013-08-19 13:14:296266 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256267
6268 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6269
6270 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196271 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256272
[email protected]3b23a222013-05-15 21:33:256273 // Since there was a request that went over the wire, the load timing
6274 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256275 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196276 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256277 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256278 }
6279}
6280
[email protected]316c1e5e2012-09-12 15:17:446281// In this test, we do a POST which the server will 302 redirect.
6282// The subsequent transaction should use GET, and should not send the
6283// Content-Type header.
6284// http://code.google.com/p/chromium/issues/detail?id=843
6285TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6286 ASSERT_TRUE(test_server_.Start());
6287
6288 const char kData[] = "hello world";
6289
6290 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196291 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366292 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196293 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076294 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446295
6296 // Set headers (some of which are specific to the POST).
6297 HttpRequestHeaders headers;
6298 headers.AddHeadersFromString(
6299 "Content-Type: multipart/form-data; "
6300 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6301 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6302 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6303 "Accept-Language: en-US,en\r\n"
6304 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6305 "Content-Length: 11\r\n"
6306 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196307 req->SetExtraRequestHeaders(headers);
6308 req->Start();
[email protected]255620da2013-08-19 13:14:296309 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446310
6311 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196312 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446313 EXPECT_EQ("text/html", mime_type);
6314
6315 const std::string& data = d.data_received();
6316
6317 // Check that the post-specific headers were stripped:
6318 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6319 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6320 EXPECT_FALSE(ContainsString(data, "Origin:"));
6321
6322 // These extra request headers should not have been stripped.
6323 EXPECT_TRUE(ContainsString(data, "Accept:"));
6324 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6325 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6326}
6327
jww5fe460ff2015-03-28 00:22:516328// The following tests check that we handle mutating the request for HTTP
6329// redirects as expected.
6330// See https://crbug.com/56373, https://crbug.com/102130, and
6331// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:446332
6333TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6334 ASSERT_TRUE(test_server_.Start());
6335
6336 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:516337 const GURL https_redirect_url =
6338 test_server_.GetURL("files/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:446339
6340 HTTPRedirectMethodTest(url, "POST", "GET", true);
6341 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6342 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516343
6344 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6345 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6346 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6347 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6348 std::string());
[email protected]316c1e5e2012-09-12 15:17:446349}
6350
6351TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6352 ASSERT_TRUE(test_server_.Start());
6353
6354 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:516355 const GURL https_redirect_url =
6356 test_server_.GetURL("files/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:446357
6358 HTTPRedirectMethodTest(url, "POST", "GET", true);
6359 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6360 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516361
6362 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6363 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6364 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6365 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6366 std::string());
[email protected]316c1e5e2012-09-12 15:17:446367}
6368
6369TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6370 ASSERT_TRUE(test_server_.Start());
6371
6372 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:516373 const GURL https_redirect_url =
6374 test_server_.GetURL("files/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:446375
6376 HTTPRedirectMethodTest(url, "POST", "GET", true);
6377 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6378 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516379
6380 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6381 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6382 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6383 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6384 std::string());
[email protected]316c1e5e2012-09-12 15:17:446385}
6386
6387TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6388 ASSERT_TRUE(test_server_.Start());
6389
6390 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:516391 const GURL https_redirect_url =
6392 test_server_.GetURL("files/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:446393
6394 HTTPRedirectMethodTest(url, "POST", "POST", 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", "POST", url.GetOrigin().spec());
6401 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:446402}
6403
[email protected]0a17aab32014-04-24 03:32:376404TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6405 ASSERT_TRUE(test_server_.Start());
6406
6407 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:516408 const GURL https_redirect_url =
6409 test_server_.GetURL("files/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:376410
6411 HTTPRedirectMethodTest(url, "POST", "POST", true);
6412 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6413 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516414
6415 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6416 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6417 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6418 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:376419}
6420
6421// Make sure that 308 responses without bodies are not treated as redirects.
6422// Certain legacy apis that pre-date the response code expect this behavior
6423// (Like Google Drive).
6424TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6425 ASSERT_TRUE(test_server_.Start());
6426
6427 TestDelegate d;
6428 const GURL url = test_server_.GetURL("files/308-without-location-header");
6429
davidben151423e2015-03-23 18:48:366430 scoped_ptr<URLRequest> request(
6431 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:376432
[email protected]f7022f32014-08-21 16:32:196433 request->Start();
[email protected]0a17aab32014-04-24 03:32:376434 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196435 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6436 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:376437 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196438 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:376439 EXPECT_EQ("This is not a redirect.", d.data_received());
6440}
6441
[email protected]f878230e2014-04-03 15:36:146442TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6443 ASSERT_TRUE(test_server_.Start());
6444
6445 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6446 GURL expected_url(test_server_.GetURL("echo#fragment"));
6447
6448 TestDelegate d;
6449 {
davidben151423e2015-03-23 18:48:366450 scoped_ptr<URLRequest> r(
6451 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146452
[email protected]f7022f32014-08-21 16:32:196453 r->Start();
[email protected]f878230e2014-04-03 15:36:146454 base::RunLoop().Run();
6455
[email protected]f7022f32014-08-21 16:32:196456 EXPECT_EQ(2U, r->url_chain().size());
6457 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6458 EXPECT_EQ(OK, r->status().error());
6459 EXPECT_EQ(original_url, r->original_url());
6460 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:146461 }
6462}
6463
[email protected]cba24642014-08-15 20:49:596464TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6465 ASSERT_TRUE(test_server_.Start());
6466
6467 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6468 GURL first_party_url("http://example.com");
6469
6470 TestDelegate d;
6471 {
davidben151423e2015-03-23 18:48:366472 scoped_ptr<URLRequest> r(
6473 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196474 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:596475
[email protected]f7022f32014-08-21 16:32:196476 r->Start();
[email protected]cba24642014-08-15 20:49:596477 base::RunLoop().Run();
6478
[email protected]f7022f32014-08-21 16:32:196479 EXPECT_EQ(2U, r->url_chain().size());
6480 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6481 EXPECT_EQ(OK, r->status().error());
6482 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596483 }
6484}
6485
6486TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6487 ASSERT_TRUE(test_server_.Start());
6488
6489 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6490 GURL original_first_party_url("http://example.com");
6491 GURL expected_first_party_url(test_server_.GetURL("echo"));
6492
6493 TestDelegate d;
6494 {
davidben151423e2015-03-23 18:48:366495 scoped_ptr<URLRequest> r(
6496 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196497 r->set_first_party_for_cookies(original_first_party_url);
6498 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:596499 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6500
[email protected]f7022f32014-08-21 16:32:196501 r->Start();
[email protected]cba24642014-08-15 20:49:596502 base::RunLoop().Run();
6503
[email protected]f7022f32014-08-21 16:32:196504 EXPECT_EQ(2U, r->url_chain().size());
6505 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6506 EXPECT_EQ(OK, r->status().error());
6507 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596508 }
6509}
6510
[email protected]316c1e5e2012-09-12 15:17:446511TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6512 ASSERT_TRUE(test_server_.Start());
6513
6514 const char kData[] = "hello world";
6515
6516 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196517 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366518 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196519 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076520 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446521 HttpRequestHeaders headers;
6522 headers.SetHeader(HttpRequestHeaders::kContentLength,
6523 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196524 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446525
6526 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196527 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096528 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446529 AddTestInterceptor()->set_main_intercept_job(job);
6530
[email protected]f7022f32014-08-21 16:32:196531 req->Start();
[email protected]255620da2013-08-19 13:14:296532 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196533 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:446534}
6535
6536TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6537 ASSERT_TRUE(test_server_.Start());
6538
6539 const char kData[] = "hello world";
6540
6541 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196542 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366543 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196544 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076545 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446546 HttpRequestHeaders headers;
6547 headers.SetHeader(HttpRequestHeaders::kContentLength,
6548 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196549 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446550
6551 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196552 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096553 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6554 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446555 AddTestInterceptor()->set_main_intercept_job(job);
6556
[email protected]f7022f32014-08-21 16:32:196557 req->Start();
[email protected]255620da2013-08-19 13:14:296558 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196559 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:446560 EXPECT_EQ(kData, d.data_received());
6561}
6562
6563// Check that default A-L header is sent.
6564TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6565 ASSERT_TRUE(test_server_.Start());
6566
[email protected]8790210c2013-12-02 05:29:536567 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:246568 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446569 TestURLRequestContext context(true);
6570 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:436571 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446572 context.Init();
6573
6574 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196575 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366576 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196577 req->Start();
[email protected]255620da2013-08-19 13:14:296578 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446579 EXPECT_EQ("en", d.data_received());
6580}
6581
6582// Check that an empty A-L header is not sent. http://crbug.com/77365.
6583TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6584 ASSERT_TRUE(test_server_.Start());
6585
[email protected]8790210c2013-12-02 05:29:536586 std::string empty_string; // Avoid most vexing parse on line below.
6587 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:246588 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446589 TestURLRequestContext context(true);
6590 context.set_network_delegate(&network_delegate);
6591 context.Init();
6592 // We override the language after initialization because empty entries
6593 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:436594 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446595
6596 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196597 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366598 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196599 req->Start();
[email protected]255620da2013-08-19 13:14:296600 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446601 EXPECT_EQ("None", d.data_received());
6602}
6603
6604// Check that if request overrides the A-L header, the default is not appended.
6605// See http://crbug.com/20894
6606TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6607 ASSERT_TRUE(test_server_.Start());
6608
6609 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196610 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366611 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446612 HttpRequestHeaders headers;
6613 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:196614 req->SetExtraRequestHeaders(headers);
6615 req->Start();
[email protected]255620da2013-08-19 13:14:296616 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446617 EXPECT_EQ(std::string("ru"), d.data_received());
6618}
6619
6620// Check that default A-E header is sent.
6621TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6622 ASSERT_TRUE(test_server_.Start());
6623
6624 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196625 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366626 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446627 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:196628 req->SetExtraRequestHeaders(headers);
6629 req->Start();
[email protected]255620da2013-08-19 13:14:296630 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446631 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6632}
6633
6634// Check that if request overrides the A-E header, the default is not appended.
6635// See http://crbug.com/47381
6636TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6637 ASSERT_TRUE(test_server_.Start());
6638
6639 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196640 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366641 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446642 HttpRequestHeaders headers;
6643 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:196644 req->SetExtraRequestHeaders(headers);
6645 req->Start();
[email protected]255620da2013-08-19 13:14:296646 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446647 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6648 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6649}
6650
[email protected]84f05432013-03-15 01:00:126651// Check that setting the A-C header sends the proper header.
6652TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:446653 ASSERT_TRUE(test_server_.Start());
6654
6655 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196656 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366657 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446658 HttpRequestHeaders headers;
6659 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:196660 req->SetExtraRequestHeaders(headers);
6661 req->Start();
[email protected]255620da2013-08-19 13:14:296662 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446663 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6664}
6665
6666// Check that default User-Agent header is sent.
6667TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6668 ASSERT_TRUE(test_server_.Start());
6669
6670 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196671 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366672 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196673 req->Start();
[email protected]255620da2013-08-19 13:14:296674 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196675 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:376676 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446677}
6678
6679// Check that if request overrides the User-Agent header,
6680// the default is not appended.
6681TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6682 ASSERT_TRUE(test_server_.Start());
6683
6684 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196685 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366686 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446687 HttpRequestHeaders headers;
6688 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:196689 req->SetExtraRequestHeaders(headers);
6690 req->Start();
[email protected]255620da2013-08-19 13:14:296691 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:356692 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446693}
6694
[email protected]ee4c30d2012-11-07 15:08:436695// Check that a NULL HttpUserAgentSettings causes the corresponding empty
6696// User-Agent header to be sent but does not send the Accept-Language and
6697// Accept-Charset headers.
6698TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6699 ASSERT_TRUE(test_server_.Start());
6700
[email protected]ceefd7fd2012-11-29 00:36:246701 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:436702 TestURLRequestContext context(true);
6703 context.set_network_delegate(&network_delegate);
6704 context.Init();
6705 // We override the HttpUserAgentSettings after initialization because empty
6706 // entries get overridden by Init().
6707 context.set_http_user_agent_settings(NULL);
6708
6709 struct {
6710 const char* request;
6711 const char* expected_response;
6712 } tests[] = { { "echoheader?Accept-Language", "None" },
6713 { "echoheader?Accept-Charset", "None" },
6714 { "echoheader?User-Agent", "" } };
6715
viettrungluue4a8b882014-10-16 06:17:386716 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:436717 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196718 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366719 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196720 req->Start();
[email protected]255620da2013-08-19 13:14:296721 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:436722 EXPECT_EQ(tests[i].expected_response, d.data_received())
6723 << " Request = \"" << tests[i].request << "\"";
6724 }
6725}
6726
[email protected]5033ab82013-03-22 20:17:466727// Make sure that URLRequest passes on its priority updates to
6728// newly-created jobs after the first one.
6729TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6730 ASSERT_TRUE(test_server_.Start());
6731
6732 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196733 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366734 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196735 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:466736
6737 scoped_refptr<URLRequestRedirectJob> redirect_job =
6738 new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196739 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096740 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:506741 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:466742
[email protected]f7022f32014-08-21 16:32:196743 req->SetPriority(LOW);
6744 req->Start();
6745 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:466746
6747 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:196748 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:506749 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:466750
6751 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:296752 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:466753 EXPECT_EQ(LOW, job->priority());
6754}
6755
[email protected]80abdad2014-03-15 00:20:546756// Check that creating a network request while entering/exiting suspend mode
6757// fails as it should. This is the only case where an HttpTransactionFactory
6758// does not return an HttpTransaction.
6759TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6760 // Create a new HttpNetworkLayer that thinks it's suspended.
6761 HttpNetworkSession::Params params;
6762 params.host_resolver = default_context_.host_resolver();
6763 params.cert_verifier = default_context_.cert_verifier();
6764 params.transport_security_state = default_context_.transport_security_state();
6765 params.proxy_service = default_context_.proxy_service();
6766 params.ssl_config_service = default_context_.ssl_config_service();
6767 params.http_auth_handler_factory =
6768 default_context_.http_auth_handler_factory();
6769 params.network_delegate = &default_network_delegate_;
6770 params.http_server_properties = default_context_.http_server_properties();
6771 scoped_ptr<HttpNetworkLayer> network_layer(
6772 new HttpNetworkLayer(new HttpNetworkSession(params)));
6773 network_layer->OnSuspend();
6774
6775 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6776 HttpCache::DefaultBackend::InMemory(0));
6777
6778 TestURLRequestContext context(true);
6779 context.set_http_transaction_factory(&http_cache);
6780 context.Init();
6781
6782 TestDelegate d;
davidben151423e2015-03-23 18:48:366783 scoped_ptr<URLRequest> req(
6784 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196785 req->Start();
[email protected]80abdad2014-03-15 00:20:546786 base::RunLoop().Run();
6787
6788 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196789 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6790 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546791}
6792
6793// Check that creating a network request while entering/exiting suspend mode
6794// fails as it should in the case there is no cache. This is the only case
6795// where an HttpTransactionFactory does not return an HttpTransaction.
6796TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6797 // Create a new HttpNetworkLayer that thinks it's suspended.
6798 HttpNetworkSession::Params params;
6799 params.host_resolver = default_context_.host_resolver();
6800 params.cert_verifier = default_context_.cert_verifier();
6801 params.transport_security_state = default_context_.transport_security_state();
6802 params.proxy_service = default_context_.proxy_service();
6803 params.ssl_config_service = default_context_.ssl_config_service();
6804 params.http_auth_handler_factory =
6805 default_context_.http_auth_handler_factory();
6806 params.network_delegate = &default_network_delegate_;
6807 params.http_server_properties = default_context_.http_server_properties();
6808 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6809 network_layer.OnSuspend();
6810
6811 TestURLRequestContext context(true);
6812 context.set_http_transaction_factory(&network_layer);
6813 context.Init();
6814
6815 TestDelegate d;
davidben151423e2015-03-23 18:48:366816 scoped_ptr<URLRequest> req(
6817 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196818 req->Start();
[email protected]80abdad2014-03-15 00:20:546819 base::RunLoop().Run();
6820
6821 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196822 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6823 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546824}
6825
bengr1bf8e942014-11-07 01:36:506826class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
6827 public:
6828 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
6829 // ideally remove the dependency on URLRequestTestJob, and maybe move these
6830 // tests into the factory tests.
6831 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
6832 }
6833
6834 void SetUpFactory() override {
6835 interceptor_ = new MockURLRequestInterceptor();
6836 job_factory_.reset(new URLRequestInterceptingJobFactory(
6837 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
6838 }
6839
6840 MockURLRequestInterceptor* interceptor() const {
6841 return interceptor_;
6842 }
6843
6844 private:
6845 MockURLRequestInterceptor* interceptor_;
6846};
6847
6848TEST_F(URLRequestInterceptorTestHTTP,
6849 NetworkDelegateNotificationOnRedirectIntercept) {
6850 interceptor()->set_intercept_redirect(true);
6851 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
6852 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
6853
6854 ASSERT_TRUE(test_server()->Start());
6855
6856 TestDelegate d;
6857 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:366858 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:506859 req->Start();
6860 base::RunLoop().Run();
6861
6862 EXPECT_TRUE(interceptor()->did_intercept_redirect());
6863 // Check we got one good response
6864 EXPECT_TRUE(req->status().is_success());
6865 if (req->status().is_success())
6866 EXPECT_EQ(200, req->response_headers()->response_code());
6867
6868 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6869 EXPECT_EQ(1, d.response_started_count());
6870 EXPECT_EQ(0, d.received_redirect_count());
6871
6872 EXPECT_EQ(1, default_network_delegate()->created_requests());
6873 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6874 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
6875}
6876
6877TEST_F(URLRequestInterceptorTestHTTP,
6878 NetworkDelegateNotificationOnErrorIntercept) {
6879 // Intercept that error and respond with an OK response.
6880 interceptor()->set_intercept_final_response(true);
6881 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
6882 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
6883 default_network_delegate()->set_can_be_intercepted_on_error(true);
6884
6885 ASSERT_TRUE(test_server()->Start());
6886
6887 TestDelegate d;
6888 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6889 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366890 &d));
bengr1bf8e942014-11-07 01:36:506891 req->set_method("GET");
6892 req->Start();
6893 base::RunLoop().Run();
6894
6895 EXPECT_TRUE(interceptor()->did_intercept_final());
6896
6897 // Check we received one good response.
6898 EXPECT_TRUE(req->status().is_success());
6899 if (req->status().is_success())
6900 EXPECT_EQ(200, req->response_headers()->response_code());
6901 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6902 EXPECT_EQ(1, d.response_started_count());
6903 EXPECT_EQ(0, d.received_redirect_count());
6904
6905 EXPECT_EQ(1, default_network_delegate()->created_requests());
6906 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6907 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
6908}
6909
6910TEST_F(URLRequestInterceptorTestHTTP,
6911 NetworkDelegateNotificationOnResponseIntercept) {
6912 // Intercept that error and respond with an OK response.
6913 interceptor()->set_intercept_final_response(true);
6914
6915 // Intercept with a real URLRequestHttpJob.
6916 interceptor()->set_use_url_request_http_job(true);
6917
6918 ASSERT_TRUE(test_server()->Start());
6919
6920 TestDelegate d;
6921 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:366922 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:506923 req->set_method("GET");
6924 req->Start();
6925 base::RunLoop().Run();
6926
6927 EXPECT_TRUE(interceptor()->did_intercept_final());
6928
6929 // Check we received one good response.
6930 EXPECT_TRUE(req->status().is_success());
6931 if (req->status().is_success())
6932 EXPECT_EQ(200, req->response_headers()->response_code());
6933 EXPECT_EQ("hello", d.data_received());
6934 EXPECT_EQ(1, d.response_started_count());
6935 EXPECT_EQ(0, d.received_redirect_count());
6936
6937 EXPECT_EQ(1, default_network_delegate()->created_requests());
6938 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
6939 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
6940}
6941
mkwst0c5eab872014-11-21 14:18:546942class URLRequestTestReferrerPolicy : public URLRequestTest {
6943 public:
6944 URLRequestTestReferrerPolicy() {}
6945
6946 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
6947 origin_server_.reset(new SpawnedTestServer(
6948 origin_type, SpawnedTestServer::kLocalhost,
6949 origin_type == SpawnedTestServer::TYPE_HTTPS
6950 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6951 : base::FilePath(
6952 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6953 ASSERT_TRUE(origin_server_->Start());
6954 }
6955
6956 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
6957 SpawnedTestServer::Type destination_type) {
6958 origin_server_.reset(new SpawnedTestServer(
6959 origin_type, SpawnedTestServer::kLocalhost,
6960 origin_type == SpawnedTestServer::TYPE_HTTPS
6961 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6962 : base::FilePath(
6963 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6964 ASSERT_TRUE(origin_server_->Start());
6965
6966 destination_server_.reset(new SpawnedTestServer(
6967 destination_type, SpawnedTestServer::kLocalhost,
6968 destination_type == SpawnedTestServer::TYPE_HTTPS
6969 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6970 : base::FilePath(
6971 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6972 ASSERT_TRUE(destination_server_->Start());
6973 }
6974
6975 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
6976 const GURL& referrer,
6977 const GURL& expected) {
6978 // Create and execute the request: we'll only have a |destination_server_|
6979 // if the origins are meant to be distinct. Otherwise, we'll use the
6980 // |origin_server_| for both endpoints.
6981 GURL destination_url =
6982 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
6983 : origin_server_->GetURL("echoheader?Referer");
6984 GURL origin_url =
6985 origin_server_->GetURL("server-redirect?" + destination_url.spec());
6986
6987 TestDelegate d;
6988 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366989 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:546990 req->set_referrer_policy(policy);
6991 req->SetReferrer(referrer.spec());
6992 req->Start();
6993 base::RunLoop().Run();
6994
6995 EXPECT_EQ(1, d.response_started_count());
6996 EXPECT_EQ(1, d.received_redirect_count());
6997 EXPECT_EQ(destination_url, req->url());
6998 EXPECT_TRUE(req->status().is_success());
6999 EXPECT_EQ(200, req->response_headers()->response_code());
7000
7001 EXPECT_EQ(expected.spec(), req->referrer());
7002 if (expected.is_empty())
7003 EXPECT_EQ("None", d.data_received());
7004 else
7005 EXPECT_EQ(expected.spec(), d.data_received());
7006 }
7007
7008 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
7009
7010 private:
7011 scoped_ptr<SpawnedTestServer> origin_server_;
7012 scoped_ptr<SpawnedTestServer> destination_server_;
7013};
7014
7015TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
7016 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
7017
7018 VerifyReferrerAfterRedirect(
7019 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7020 origin_server()->GetURL("path/to/file.html"),
7021 origin_server()->GetURL("path/to/file.html"));
7022
7023 VerifyReferrerAfterRedirect(
7024 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7025 origin_server()->GetURL("path/to/file.html"),
7026 origin_server()->GetURL("path/to/file.html"));
7027
7028 VerifyReferrerAfterRedirect(
7029 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7030 origin_server()->GetURL("path/to/file.html"),
7031 origin_server()->GetURL("path/to/file.html"));
7032
7033 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7034 origin_server()->GetURL("path/to/file.html"),
7035 origin_server()->GetURL("path/to/file.html"));
7036}
7037
7038TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
7039 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7040 SpawnedTestServer::TYPE_HTTP);
7041
7042 VerifyReferrerAfterRedirect(
7043 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7044 origin_server()->GetURL("path/to/file.html"),
7045 origin_server()->GetURL("path/to/file.html"));
7046
7047 VerifyReferrerAfterRedirect(
7048 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7049 origin_server()->GetURL("path/to/file.html"),
7050 origin_server()->GetURL(std::string()));
7051
7052 VerifyReferrerAfterRedirect(
7053 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7054 origin_server()->GetURL("path/to/file.html"),
7055 origin_server()->GetURL(std::string()));
7056
7057 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7058 origin_server()->GetURL("path/to/file.html"),
7059 origin_server()->GetURL("path/to/file.html"));
7060}
7061
7062TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
7063 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
7064
7065 VerifyReferrerAfterRedirect(
7066 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7067 origin_server()->GetURL("path/to/file.html"),
7068 origin_server()->GetURL("path/to/file.html"));
7069
7070 VerifyReferrerAfterRedirect(
7071 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7072 origin_server()->GetURL("path/to/file.html"),
7073 origin_server()->GetURL("path/to/file.html"));
7074
7075 VerifyReferrerAfterRedirect(
7076 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7077 origin_server()->GetURL("path/to/file.html"),
7078 origin_server()->GetURL("path/to/file.html"));
7079
7080 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7081 origin_server()->GetURL("path/to/file.html"),
7082 origin_server()->GetURL("path/to/file.html"));
7083}
7084
7085TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7086 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7087 SpawnedTestServer::TYPE_HTTPS);
7088
7089 VerifyReferrerAfterRedirect(
7090 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7091 origin_server()->GetURL("path/to/file.html"),
7092 origin_server()->GetURL("path/to/file.html"));
7093
7094 VerifyReferrerAfterRedirect(
7095 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7096 origin_server()->GetURL("path/to/file.html"),
7097 origin_server()->GetURL(std::string()));
7098
7099 VerifyReferrerAfterRedirect(
7100 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7101 origin_server()->GetURL("path/to/file.html"),
7102 origin_server()->GetURL(std::string()));
7103
7104 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7105 origin_server()->GetURL("path/to/file.html"),
7106 origin_server()->GetURL("path/to/file.html"));
7107}
7108
7109TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7110 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7111 SpawnedTestServer::TYPE_HTTPS);
7112
7113 VerifyReferrerAfterRedirect(
7114 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7115 origin_server()->GetURL("path/to/file.html"),
7116 origin_server()->GetURL("path/to/file.html"));
7117
7118 VerifyReferrerAfterRedirect(
7119 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7120 origin_server()->GetURL("path/to/file.html"),
7121 origin_server()->GetURL(std::string()));
7122
7123 VerifyReferrerAfterRedirect(
7124 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7125 origin_server()->GetURL("path/to/file.html"),
7126 origin_server()->GetURL(std::string()));
7127
7128 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7129 origin_server()->GetURL("path/to/file.html"),
7130 origin_server()->GetURL("path/to/file.html"));
7131}
7132
7133TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7134 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7135 SpawnedTestServer::TYPE_HTTP);
7136
7137 VerifyReferrerAfterRedirect(
7138 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7139 origin_server()->GetURL("path/to/file.html"), GURL());
7140
7141 VerifyReferrerAfterRedirect(
7142 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7143 origin_server()->GetURL("path/to/file.html"), GURL());
7144
7145 VerifyReferrerAfterRedirect(
7146 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7147 origin_server()->GetURL("path/to/file.html"),
7148 origin_server()->GetURL(std::string()));
7149
7150 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7151 origin_server()->GetURL("path/to/file.html"),
7152 origin_server()->GetURL("path/to/file.html"));
7153}
7154
[email protected]73e0bba2009-02-19 22:57:097155class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507156 public:
[email protected]ef2bf422012-05-11 03:27:097157 HTTPSRequestTest() : default_context_(true) {
7158 default_context_.set_network_delegate(&default_network_delegate_);
7159 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507160 }
dcheng67be2b1f2014-10-27 21:47:297161 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507162
7163 protected:
[email protected]ceefd7fd2012-11-29 00:36:247164 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097165 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467166};
7167
[email protected]c044616e2013-02-20 02:01:267168TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227169 SpawnedTestServer test_server(
7170 SpawnedTestServer::TYPE_HTTPS,
7171 SpawnedTestServer::kLocalhost,
7172 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117173 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467174
[email protected]ea224582008-12-07 20:25:467175 TestDelegate d;
7176 {
[email protected]f7022f32014-08-21 16:32:197177 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367178 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197179 r->Start();
7180 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467181
[email protected]255620da2013-08-19 13:14:297182 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467183
7184 EXPECT_EQ(1, d.response_started_count());
7185 EXPECT_FALSE(d.received_data_before_response());
7186 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197187 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197188 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197189 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197190 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197191 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467192 }
[email protected]ea224582008-12-07 20:25:467193}
7194
[email protected]5774ada2010-07-15 06:30:547195TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227196 SpawnedTestServer::SSLOptions ssl_options(
7197 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7198 SpawnedTestServer test_server(
7199 SpawnedTestServer::TYPE_HTTPS,
7200 ssl_options,
7201 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117202 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337203
7204 bool err_allowed = true;
7205 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7206 TestDelegate d;
7207 {
7208 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197209 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367210 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337211
[email protected]f7022f32014-08-21 16:32:197212 r->Start();
7213 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337214
[email protected]255620da2013-08-19 13:14:297215 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337216
7217 EXPECT_EQ(1, d.response_started_count());
7218 EXPECT_FALSE(d.received_data_before_response());
7219 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177220 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337221 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197222 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177223 } else {
[email protected]bacff652009-03-31 17:50:337224 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177225 }
[email protected]bacff652009-03-31 17:50:337226 }
7227 }
7228}
7229
[email protected]5774ada2010-07-15 06:30:547230TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227231 SpawnedTestServer::SSLOptions ssl_options(
7232 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7233 SpawnedTestServer test_server(
7234 SpawnedTestServer::TYPE_HTTPS,
7235 ssl_options,
7236 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117237 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337238
7239 // Iterate from false to true, just so that we do the opposite of the
7240 // previous test in order to increase test coverage.
7241 bool err_allowed = false;
7242 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7243 TestDelegate d;
7244 {
7245 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197246 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367247 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337248
[email protected]f7022f32014-08-21 16:32:197249 r->Start();
7250 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337251
[email protected]255620da2013-08-19 13:14:297252 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337253
7254 EXPECT_EQ(1, d.response_started_count());
7255 EXPECT_FALSE(d.received_data_before_response());
7256 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177257 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337258 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197259 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177260 } else {
[email protected]bacff652009-03-31 17:50:337261 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177262 }
[email protected]bacff652009-03-31 17:50:337263 }
7264 }
7265}
[email protected]73e0bba2009-02-19 22:57:097266
davidbena4c9d062015-04-03 22:34:257267// Tests that servers which require a deprecated cipher suite still work.
7268TEST_F(HTTPSRequestTest, CipherFallbackTest) {
vishal.b62985ca92015-04-17 08:45:517269 TestNetLog net_log;
davidbena4c9d062015-04-03 22:34:257270 default_context_.set_net_log(&net_log);
7271
7272 SpawnedTestServer::SSLOptions ssl_options;
7273 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
7274 SpawnedTestServer test_server(
7275 SpawnedTestServer::TYPE_HTTPS, ssl_options,
7276 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7277 ASSERT_TRUE(test_server.Start());
7278
7279 TestDelegate d;
7280 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7281 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7282 r->Start();
7283 EXPECT_TRUE(r->is_pending());
7284
7285 base::RunLoop().Run();
7286
7287 EXPECT_EQ(1, d.response_started_count());
7288 EXPECT_FALSE(d.received_data_before_response());
7289 EXPECT_NE(0, d.bytes_received());
7290 CheckSSLInfo(r->ssl_info());
7291 EXPECT_EQ(test_server.host_port_pair().host(), r->GetSocketAddress().host());
7292 EXPECT_EQ(test_server.host_port_pair().port(), r->GetSocketAddress().port());
7293
7294 // No version downgrade should have been necessary.
7295 EXPECT_FALSE(r->ssl_info().connection_status &
7296 SSL_CONNECTION_VERSION_FALLBACK);
7297 int expected_version = SSL_CONNECTION_VERSION_TLS1_2;
7298 if (SSLClientSocket::GetMaxSupportedSSLVersion() <
7299 SSL_PROTOCOL_VERSION_TLS1_2) {
7300 expected_version = SSL_CONNECTION_VERSION_TLS1_1;
7301 }
7302 EXPECT_EQ(expected_version,
7303 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
7304
mmenke43758e62015-05-04 21:09:467305 TestNetLogEntry::List entries;
davidbena4c9d062015-04-03 22:34:257306 net_log.GetEntries(&entries);
7307 ExpectLogContainsSomewhere(entries, 0, NetLog::TYPE_SSL_CIPHER_FALLBACK,
7308 NetLog::PHASE_NONE);
7309}
7310
[email protected]316c1e5e2012-09-12 15:17:447311// This tests that a load of www.google.com with a certificate error sets
7312// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7313// the interstitial to be fatal.
7314TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227315 SpawnedTestServer::SSLOptions ssl_options(
7316 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7317 SpawnedTestServer test_server(
7318 SpawnedTestServer::TYPE_HTTPS,
7319 ssl_options,
7320 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447321 ASSERT_TRUE(test_server.Start());
7322
7323 // We require that the URL be www.google.com in order to pick up the
7324 // preloaded HSTS entries in the TransportSecurityState. This means that we
7325 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247326 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447327
7328 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247329 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447330 TestURLRequestContext context(true);
7331 context.set_network_delegate(&network_delegate);
7332 context.set_host_resolver(&host_resolver);
7333 TransportSecurityState transport_security_state;
7334 context.set_transport_security_state(&transport_security_state);
7335 context.Init();
7336
7337 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197338 scoped_ptr<URLRequest> r(context.CreateRequest(
7339 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367340 test_server.host_port_pair().port())),
7341 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447342
[email protected]f7022f32014-08-21 16:32:197343 r->Start();
7344 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447345
[email protected]255620da2013-08-19 13:14:297346 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447347
7348 EXPECT_EQ(1, d.response_started_count());
7349 EXPECT_FALSE(d.received_data_before_response());
7350 EXPECT_TRUE(d.have_certificate_errors());
7351 EXPECT_TRUE(d.certificate_errors_are_fatal());
7352}
7353
7354// This tests that cached HTTPS page loads do not cause any updates to the
7355// TransportSecurityState.
7356TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7357 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7358 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227359 SpawnedTestServer::SSLOptions ssl_options(
7360 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7361 SpawnedTestServer test_server(
7362 SpawnedTestServer::TYPE_HTTPS,
7363 ssl_options,
7364 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447365 ASSERT_TRUE(test_server.Start());
7366
[email protected]9e6968d2014-05-07 21:46:267367 // We require that the URL be www.google.com in order to pick up the static
7368 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7369 // that we have to use a MockHostResolver in order to direct www.google.com to
7370 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447371
7372 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247373 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447374 TestURLRequestContext context(true);
7375 context.set_network_delegate(&network_delegate);
7376 context.set_host_resolver(&host_resolver);
7377 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267378
7379 TransportSecurityState::DomainState static_domain_state;
7380 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127381 "www.google.com", &static_domain_state));
[email protected]316c1e5e2012-09-12 15:17:447382 context.set_transport_security_state(&transport_security_state);
7383 context.Init();
7384
[email protected]9e6968d2014-05-07 21:46:267385 TransportSecurityState::DomainState dynamic_domain_state;
7386 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7387 "www.google.com", &dynamic_domain_state));
7388
[email protected]316c1e5e2012-09-12 15:17:447389 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197390 scoped_ptr<URLRequest> r(context.CreateRequest(
7391 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367392 test_server.host_port_pair().port())),
7393 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447394
[email protected]f7022f32014-08-21 16:32:197395 r->Start();
7396 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447397
[email protected]255620da2013-08-19 13:14:297398 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447399
7400 EXPECT_EQ(1, d.response_started_count());
7401 EXPECT_FALSE(d.received_data_before_response());
7402 EXPECT_TRUE(d.have_certificate_errors());
7403 EXPECT_TRUE(d.certificate_errors_are_fatal());
7404
[email protected]9e6968d2014-05-07 21:46:267405 // Get a fresh copy of the states, and check that they haven't changed.
7406 TransportSecurityState::DomainState new_static_domain_state;
7407 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127408 "www.google.com", &new_static_domain_state));
[email protected]9e6968d2014-05-07 21:46:267409 TransportSecurityState::DomainState new_dynamic_domain_state;
7410 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7411 "www.google.com", &new_dynamic_domain_state));
7412
7413 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
7414 static_domain_state.sts.upgrade_mode);
7415 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
7416 static_domain_state.sts.include_subdomains);
7417 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
7418 static_domain_state.pkp.include_subdomains);
7419 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
7420 static_domain_state.pkp.spki_hashes));
7421 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
7422 static_domain_state.pkp.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:447423}
7424
[email protected]8ccc69f2012-11-28 19:52:147425// Make sure HSTS preserves a POST request's method and body.
7426TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7427 static const char kData[] = "hello world";
7428
[email protected]ce7d0cbc2013-05-03 18:57:227429 SpawnedTestServer::SSLOptions ssl_options(
7430 SpawnedTestServer::SSLOptions::CERT_OK);
7431 SpawnedTestServer test_server(
7432 SpawnedTestServer::TYPE_HTTPS,
7433 ssl_options,
7434 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:147435 ASSERT_TRUE(test_server.Start());
7436
7437
7438 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7439 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:227440 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7441 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:147442 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:147443
7444 // Force https for www.somewhere.com.
7445 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:207446 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7447 bool include_subdomains = false;
7448 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7449 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:147450
7451 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7452
7453 TestURLRequestContext context(true);
7454 context.set_host_resolver(&host_resolver);
7455 context.set_transport_security_state(&transport_security_state);
7456 context.set_network_delegate(&network_delegate);
7457 context.Init();
7458
7459 TestDelegate d;
7460 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7461 // cause a certificate error. Ignore the error.
7462 d.set_allow_certificate_errors(true);
7463
[email protected]f7022f32014-08-21 16:32:197464 scoped_ptr<URLRequest> req(context.CreateRequest(
7465 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:367466 test_server.host_port_pair().port())),
7467 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197468 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077469 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:147470
[email protected]f7022f32014-08-21 16:32:197471 req->Start();
[email protected]255620da2013-08-19 13:14:297472 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:147473
[email protected]f7022f32014-08-21 16:32:197474 EXPECT_EQ("https", req->url().scheme());
7475 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:147476 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:407477
7478 LoadTimingInfo load_timing_info;
7479 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7480 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7481 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:147482}
7483
rob4e0be1f2014-09-11 23:40:227484// Make sure that the CORS headers are added to cross-origin HSTS redirects.
7485TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7486 static const char kOriginHeaderValue[] = "http://www.example.com";
7487
7488 SpawnedTestServer::SSLOptions ssl_options(
7489 SpawnedTestServer::SSLOptions::CERT_OK);
7490 SpawnedTestServer test_server(
7491 SpawnedTestServer::TYPE_HTTPS,
7492 ssl_options,
7493 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7494 ASSERT_TRUE(test_server.Start());
7495
7496 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7497 // address, so a MockHostResolver is needed to redirect example.net to the
7498 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7499 MockHostResolver host_resolver;
7500
7501 TransportSecurityState transport_security_state;
7502 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7503 bool include_subdomains = false;
7504 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7505
7506 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7507
7508 MockCertVerifier cert_verifier;
7509 cert_verifier.set_default_result(OK);
7510
7511 TestURLRequestContext context(true);
7512 context.set_host_resolver(&host_resolver);
7513 context.set_transport_security_state(&transport_security_state);
7514 context.set_network_delegate(&network_delegate);
7515 context.set_cert_verifier(&cert_verifier);
7516 context.Init();
7517
7518 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7519 test_server.host_port_pair().port()));
7520 url::Replacements<char> replacements;
7521 const char kNewScheme[] = "https";
7522 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7523 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7524
7525 TestDelegate d;
7526 // Quit on redirect to allow response header inspection upon redirect.
7527 d.set_quit_on_redirect(true);
7528
davidben151423e2015-03-23 18:48:367529 scoped_ptr<URLRequest> req(
7530 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:227531 // Set Origin header to simulate a cross-origin request.
7532 HttpRequestHeaders request_headers;
7533 request_headers.SetHeader("Origin", kOriginHeaderValue);
7534 req->SetExtraRequestHeaders(request_headers);
7535
7536 req->Start();
7537 base::RunLoop().Run();
7538
7539 EXPECT_EQ(1, d.received_redirect_count());
7540
7541 const HttpResponseHeaders* headers = req->response_headers();
7542 std::string redirect_location;
7543 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7544 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7545
7546 std::string received_cors_header;
7547 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7548 &received_cors_header));
7549 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7550}
7551
Adam Ricecb76ac62015-02-20 05:33:257552// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
7553// are performed in net/websockets/websocket_end_to_end_test.cc.
7554TEST(WebSocketURLRequestTest, HSTSApplied) {
7555 TestNetworkDelegate network_delegate;
7556 TransportSecurityState transport_security_state;
7557 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7558 bool include_subdomains = false;
7559 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7560 TestURLRequestContext context(true);
7561 context.set_transport_security_state(&transport_security_state);
7562 context.set_network_delegate(&network_delegate);
7563 context.Init();
7564 GURL ws_url("ws://example.net/echo");
7565 TestDelegate delegate;
7566 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367567 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:257568 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
7569 EXPECT_TRUE(ws_url.SchemeIs("wss"));
7570}
7571
[email protected]316c1e5e2012-09-12 15:17:447572namespace {
7573
7574class SSLClientAuthTestDelegate : public TestDelegate {
7575 public:
7576 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7577 }
dchengb03027d2014-10-21 12:00:207578 void OnCertificateRequested(URLRequest* request,
7579 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:447580 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:347581 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:447582 }
7583 int on_certificate_requested_count() {
7584 return on_certificate_requested_count_;
7585 }
7586 private:
7587 int on_certificate_requested_count_;
7588};
7589
7590} // namespace
7591
7592// TODO(davidben): Test the rest of the code. Specifically,
7593// - Filtering which certificates to select.
7594// - Sending a certificate back.
7595// - Getting a certificate request in an SSL renegotiation sending the
7596// HTTP request.
7597TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227598 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447599 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:227600 SpawnedTestServer test_server(
7601 SpawnedTestServer::TYPE_HTTPS,
7602 ssl_options,
7603 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447604 ASSERT_TRUE(test_server.Start());
7605
7606 SSLClientAuthTestDelegate d;
7607 {
[email protected]f7022f32014-08-21 16:32:197608 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367609 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447610
[email protected]f7022f32014-08-21 16:32:197611 r->Start();
7612 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447613
[email protected]255620da2013-08-19 13:14:297614 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447615
7616 EXPECT_EQ(1, d.on_certificate_requested_count());
7617 EXPECT_FALSE(d.received_data_before_response());
7618 EXPECT_EQ(0, d.bytes_received());
7619
7620 // Send no certificate.
7621 // TODO(davidben): Get temporary client cert import (with keys) working on
7622 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:197623 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:447624
[email protected]255620da2013-08-19 13:14:297625 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447626
7627 EXPECT_EQ(1, d.response_started_count());
7628 EXPECT_FALSE(d.received_data_before_response());
7629 EXPECT_NE(0, d.bytes_received());
7630 }
7631}
7632
7633TEST_F(HTTPSRequestTest, ResumeTest) {
7634 // Test that we attempt a session resume when making two connections to the
7635 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:227636 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447637 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227638 SpawnedTestServer test_server(
7639 SpawnedTestServer::TYPE_HTTPS,
7640 ssl_options,
7641 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447642 ASSERT_TRUE(test_server.Start());
7643
7644 SSLClientSocket::ClearSessionCache();
7645
7646 {
7647 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197648 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367649 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447650
[email protected]f7022f32014-08-21 16:32:197651 r->Start();
7652 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447653
[email protected]255620da2013-08-19 13:14:297654 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447655
7656 EXPECT_EQ(1, d.response_started_count());
7657 }
7658
7659 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7660 CloseAllConnections();
7661
7662 {
7663 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197664 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367665 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447666
[email protected]f7022f32014-08-21 16:32:197667 r->Start();
7668 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447669
[email protected]255620da2013-08-19 13:14:297670 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447671
7672 // The response will look like;
7673 // insert abc
7674 // lookup abc
7675 // insert xyz
7676 //
7677 // With a newline at the end which makes the split think that there are
7678 // four lines.
7679
7680 EXPECT_EQ(1, d.response_started_count());
7681 std::vector<std::string> lines;
7682 base::SplitString(d.data_received(), '\n', &lines);
7683 ASSERT_EQ(4u, lines.size()) << d.data_received();
7684
7685 std::string session_id;
7686
7687 for (size_t i = 0; i < 2; i++) {
7688 std::vector<std::string> parts;
7689 base::SplitString(lines[i], '\t', &parts);
7690 ASSERT_EQ(2u, parts.size());
7691 if (i == 0) {
7692 EXPECT_EQ("insert", parts[0]);
7693 session_id = parts[1];
7694 } else {
7695 EXPECT_EQ("lookup", parts[0]);
7696 EXPECT_EQ(session_id, parts[1]);
7697 }
7698 }
7699 }
7700}
7701
Adam Langley32352ad2014-10-14 22:31:007702// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7703// the result of fetching "ssl-session-cache" from the test server, indicates
7704// that exactly two different sessions were inserted, with no lookups etc.
7705static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7706 std::vector<std::string> lines;
7707 base::SplitString(session_info, '\n', &lines);
7708 ASSERT_EQ(3u, lines.size()) << session_info;
7709
7710 std::string session_id;
7711 for (size_t i = 0; i < 2; i++) {
7712 std::vector<std::string> parts;
7713 base::SplitString(lines[i], '\t', &parts);
7714 ASSERT_EQ(2u, parts.size());
7715 EXPECT_EQ("insert", parts[0]);
7716 if (i == 0) {
7717 session_id = parts[1];
7718 } else {
7719 EXPECT_NE(session_id, parts[1]);
7720 }
7721 }
7722}
7723
[email protected]316c1e5e2012-09-12 15:17:447724TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7725 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7726 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:227727 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447728 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227729 SpawnedTestServer test_server(
7730 SpawnedTestServer::TYPE_HTTPS,
7731 ssl_options,
7732 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447733 ASSERT_TRUE(test_server.Start());
7734
7735 SSLClientSocket::ClearSessionCache();
7736
7737 {
7738 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197739 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367740 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447741
[email protected]f7022f32014-08-21 16:32:197742 r->Start();
7743 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447744
[email protected]255620da2013-08-19 13:14:297745 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447746
7747 EXPECT_EQ(1, d.response_started_count());
7748 }
7749
7750 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7751 HttpNetworkSession::Params params;
7752 params.host_resolver = default_context_.host_resolver();
7753 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:117754 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:447755 params.proxy_service = default_context_.proxy_service();
7756 params.ssl_config_service = default_context_.ssl_config_service();
7757 params.http_auth_handler_factory =
7758 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:417759 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:447760 params.http_server_properties = default_context_.http_server_properties();
7761 params.ssl_session_cache_shard = "alternate";
7762
[email protected]cba24642014-08-15 20:49:597763 scoped_ptr<HttpCache> cache(new HttpCache(
7764 new HttpNetworkSession(params),
7765 HttpCache::DefaultBackend::InMemory(0)));
[email protected]316c1e5e2012-09-12 15:17:447766
7767 default_context_.set_http_transaction_factory(cache.get());
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 // insert xyz
7782 //
7783 // With a newline at the end which makes the split think that there are
7784 // three lines.
7785
7786 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:007787 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447788 }
7789}
7790
davidben8ecc3072014-09-03 23:19:097791#if defined(OS_WIN)
7792
7793namespace {
7794
7795bool IsECDSACipherSuite(uint16_t cipher_suite) {
7796 const char* key_exchange;
7797 const char* cipher;
7798 const char* mac;
7799 bool is_aead;
7800 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7801 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7802}
7803
7804} // namespace
7805
7806// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7807// verified.
davidben9399c952014-10-07 04:09:117808TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:097809 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7810 LOG(INFO) << "Skipping test on this version.";
7811 return;
7812 }
7813
7814 SpawnedTestServer test_server(
7815 SpawnedTestServer::TYPE_HTTPS,
7816 SpawnedTestServer::kLocalhost,
7817 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7818 ASSERT_TRUE(test_server.Start());
7819
7820 TestDelegate d;
7821 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367822 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:097823 r->Start();
7824 EXPECT_TRUE(r->is_pending());
7825
7826 base::RunLoop().Run();
7827
7828 EXPECT_EQ(1, d.response_started_count());
7829 std::vector<std::string> lines;
7830 base::SplitString(d.data_received(), '\n', &lines);
7831
7832 for (size_t i = 0; i < lines.size(); i++) {
7833 int cipher_suite;
7834 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7835 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7836 << "ClientHello advertised " << cipher_suite;
7837 }
7838}
7839
7840#endif // OS_WIN
7841
Adam Langley32352ad2014-10-14 22:31:007842class TestSSLConfigService : public SSLConfigService {
7843 public:
7844 TestSSLConfigService(bool ev_enabled,
7845 bool online_rev_checking,
7846 bool rev_checking_required_local_anchors)
7847 : ev_enabled_(ev_enabled),
7848 online_rev_checking_(online_rev_checking),
7849 rev_checking_required_local_anchors_(
7850 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:027851 min_version_(kDefaultSSLVersionMin),
7852 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7853
7854 void set_min_version(uint16 version) {
7855 min_version_ = version;
7856 }
Adam Langley32352ad2014-10-14 22:31:007857
7858 void set_fallback_min_version(uint16 version) {
7859 fallback_min_version_ = version;
7860 }
7861
7862 // SSLConfigService:
dchengb03027d2014-10-21 12:00:207863 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:007864 *config = SSLConfig();
7865 config->rev_checking_enabled = online_rev_checking_;
7866 config->verify_ev_cert = ev_enabled_;
7867 config->rev_checking_required_local_anchors =
7868 rev_checking_required_local_anchors_;
7869 if (fallback_min_version_) {
7870 config->version_fallback_min = fallback_min_version_;
7871 }
Adam Langleyac6f24b42014-10-31 20:24:027872 if (min_version_) {
7873 config->version_min = min_version_;
7874 }
Adam Langley32352ad2014-10-14 22:31:007875 }
7876
7877 protected:
dchengb03027d2014-10-21 12:00:207878 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:007879
7880 private:
7881 const bool ev_enabled_;
7882 const bool online_rev_checking_;
7883 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:027884 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:007885 uint16 fallback_min_version_;
7886};
7887
7888class FallbackTestURLRequestContext : public TestURLRequestContext {
7889 public:
7890 explicit FallbackTestURLRequestContext(bool delay_initialization)
7891 : TestURLRequestContext(delay_initialization) {}
7892
7893 void set_fallback_min_version(uint16 version) {
7894 TestSSLConfigService *ssl_config_service =
7895 new TestSSLConfigService(true /* check for EV */,
7896 false /* online revocation checking */,
7897 false /* require rev. checking for local
7898 anchors */);
Adam Langley32352ad2014-10-14 22:31:007899 ssl_config_service->set_fallback_min_version(version);
7900 set_ssl_config_service(ssl_config_service);
7901 }
7902};
7903
[email protected]48d2b7c52014-06-27 01:16:557904class HTTPSFallbackTest : public testing::Test {
7905 public:
Adam Langley32352ad2014-10-14 22:31:007906 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:297907 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:557908
7909 protected:
7910 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
7911 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:007912 context_.Init();
7913 delegate_.set_allow_certificate_errors(true);
7914
[email protected]48d2b7c52014-06-27 01:16:557915 SpawnedTestServer test_server(
7916 SpawnedTestServer::TYPE_HTTPS,
7917 ssl_options,
7918 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7919 ASSERT_TRUE(test_server.Start());
7920
davidben151423e2015-03-23 18:48:367921 request_ = context_.CreateRequest(test_server.GetURL(std::string()),
7922 DEFAULT_PRIORITY, &delegate_);
[email protected]48d2b7c52014-06-27 01:16:557923 request_->Start();
7924
7925 base::RunLoop().Run();
7926 }
7927
Adam Langley32352ad2014-10-14 22:31:007928 void set_fallback_min_version(uint16 version) {
7929 context_.set_fallback_min_version(version);
7930 }
7931
[email protected]48d2b7c52014-06-27 01:16:557932 void ExpectConnection(int version) {
7933 EXPECT_EQ(1, delegate_.response_started_count());
7934 EXPECT_NE(0, delegate_.bytes_received());
7935 EXPECT_EQ(version, SSLConnectionStatusToVersion(
7936 request_->ssl_info().connection_status));
7937 EXPECT_TRUE(request_->ssl_info().connection_status &
7938 SSL_CONNECTION_VERSION_FALLBACK);
7939 }
7940
7941 void ExpectFailure(int error) {
7942 EXPECT_EQ(1, delegate_.response_started_count());
7943 EXPECT_FALSE(request_->status().is_success());
7944 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
7945 EXPECT_EQ(error, request_->status().error());
7946 }
7947
7948 private:
7949 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:007950 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:557951 scoped_ptr<URLRequest> request_;
7952};
7953
7954// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
7955// than necessary.
7956TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
7957 SpawnedTestServer::SSLOptions ssl_options(
7958 SpawnedTestServer::SSLOptions::CERT_OK);
7959 ssl_options.tls_intolerant =
7960 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7961
7962 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7963 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7964}
7965
7966// This test is disabled on Android because the remote test server doesn't cause
7967// a TCP reset.
7968#if !defined(OS_ANDROID)
7969// Tests fallback to TLS 1.0 on connection reset.
7970TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
7971 SpawnedTestServer::SSLOptions ssl_options(
7972 SpawnedTestServer::SSLOptions::CERT_OK);
7973 ssl_options.tls_intolerant =
7974 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7975 ssl_options.tls_intolerance_type =
7976 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7977
7978 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7979 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7980}
7981#endif // !OS_ANDROID
7982
[email protected]12833302014-07-02 01:57:317983// Tests that we don't fallback on handshake failure with servers that implement
7984// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:557985TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:557986 SpawnedTestServer::SSLOptions ssl_options(
7987 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:437988 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:557989 // a version fallback.
7990 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:437991 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:557992 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7993 // connections are rejected.
7994 ssl_options.fallback_scsv_enabled = true;
7995
7996 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7997
7998 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
7999 // intolerance. If the fallback SCSV is processed when the original error
8000 // that caused the fallback should be returned, which should be
8001 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8002 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8003}
8004
[email protected]12833302014-07-02 01:57:318005// Tests that we don't fallback on connection closed with servers that implement
8006// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318007TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318008 SpawnedTestServer::SSLOptions ssl_options(
8009 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438010 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318011 // a version fallback.
8012 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438013 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318014 ssl_options.tls_intolerance_type =
8015 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8016 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8017 // connections are rejected.
8018 ssl_options.fallback_scsv_enabled = true;
8019
8020 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8021
8022 // The original error should be replayed on rejected fallback.
8023 ExpectFailure(ERR_CONNECTION_CLOSED);
8024}
8025
davidbenb937d6c2015-05-14 04:53:428026// Tests that the SSLv3 fallback doesn't happen.
[email protected]48d2b7c52014-06-27 01:16:558027TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
8028 SpawnedTestServer::SSLOptions ssl_options(
8029 SpawnedTestServer::SSLOptions::CERT_OK);
8030 ssl_options.tls_intolerant =
8031 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8032
8033 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
Adam Langleyac6f24b42014-10-31 20:24:028034 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
Adam Langley32352ad2014-10-14 22:31:008035}
8036
davidbenb937d6c2015-05-14 04:53:428037// Tests that the TLSv1 fallback triggers on closed connections.
[email protected]48d2b7c52014-06-27 01:16:558038TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
8039 SpawnedTestServer::SSLOptions ssl_options(
8040 SpawnedTestServer::SSLOptions::CERT_OK);
8041 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428042 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558043 ssl_options.tls_intolerance_type =
8044 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
[email protected]48d2b7c52014-06-27 01:16:558045
8046 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb937d6c2015-05-14 04:53:428047 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
[email protected]48d2b7c52014-06-27 01:16:558048}
8049
davidbenb937d6c2015-05-14 04:53:428050// Test that fallback probe connections don't cause sessions to be cached.
8051TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008052 SpawnedTestServer::SSLOptions ssl_options(
8053 SpawnedTestServer::SSLOptions::CERT_OK);
8054 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428055 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008056 ssl_options.tls_intolerance_type =
8057 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8058 ssl_options.record_resume = true;
8059
8060 SpawnedTestServer test_server(
8061 SpawnedTestServer::TYPE_HTTPS,
8062 ssl_options,
8063 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8064 ASSERT_TRUE(test_server.Start());
8065
8066 SSLClientSocket::ClearSessionCache();
8067
davidbenb937d6c2015-05-14 04:53:428068 // Make a connection that does a probe fallback to TLSv1 but fails because
8069 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008070 // be inserted locally.
8071 {
8072 TestDelegate delegate;
8073 FallbackTestURLRequestContext context(true);
8074
davidbenb937d6c2015-05-14 04:53:428075 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008076 context.Init();
8077 scoped_ptr<URLRequest> request(context.CreateRequest(
davidben151423e2015-03-23 18:48:368078 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008079 request->Start();
8080
8081 base::RunLoop().Run();
8082
8083 EXPECT_EQ(1, delegate.response_started_count());
8084 EXPECT_FALSE(request->status().is_success());
8085 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8086 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8087 request->status().error());
8088 }
8089
davidbenb937d6c2015-05-14 04:53:428090 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008091 {
8092 TestDelegate delegate;
8093 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428094 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008095
8096 context.Init();
davidben151423e2015-03-23 18:48:368097 scoped_ptr<URLRequest> request(context.CreateRequest(
8098 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008099 request->Start();
8100
8101 base::RunLoop().Run();
8102
8103 EXPECT_EQ(1, delegate.response_started_count());
8104 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428105 EXPECT_EQ(
8106 SSL_CONNECTION_VERSION_TLS1,
8107 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008108 EXPECT_TRUE(request->ssl_info().connection_status &
8109 SSL_CONNECTION_VERSION_FALLBACK);
8110
8111 std::vector<std::string> lines;
8112 // If no sessions were cached then the server should have seen two sessions
8113 // inserted with no lookups.
8114 AssertTwoDistinctSessionsInserted(delegate.data_received());
8115 }
8116}
8117
[email protected]a8fed1742013-12-27 02:14:248118class HTTPSSessionTest : public testing::Test {
8119 public:
8120 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598121 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248122
8123 default_context_.set_network_delegate(&default_network_delegate_);
8124 default_context_.set_cert_verifier(&cert_verifier_);
8125 default_context_.Init();
8126 }
dcheng67be2b1f2014-10-27 21:47:298127 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248128
8129 protected:
8130 MockCertVerifier cert_verifier_;
8131 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8132 TestURLRequestContext default_context_;
8133};
8134
8135// Tests that session resumption is not attempted if an invalid certificate
8136// is presented.
8137TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8138 SpawnedTestServer::SSLOptions ssl_options;
8139 ssl_options.record_resume = true;
8140 SpawnedTestServer test_server(
8141 SpawnedTestServer::TYPE_HTTPS,
8142 ssl_options,
8143 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8144 ASSERT_TRUE(test_server.Start());
8145
8146 SSLClientSocket::ClearSessionCache();
8147
8148 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598149 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248150 {
8151 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198152 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368153 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248154
[email protected]f7022f32014-08-21 16:32:198155 r->Start();
8156 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248157
8158 base::RunLoop().Run();
8159
8160 EXPECT_EQ(1, d.response_started_count());
8161 }
8162
8163 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8164 CloseAllConnections();
8165
8166 // Now change the certificate to be acceptable (so that the response is
8167 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598168 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248169 {
8170 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198171 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368172 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248173
[email protected]f7022f32014-08-21 16:32:198174 r->Start();
8175 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248176
8177 base::RunLoop().Run();
8178
8179 // The response will look like;
8180 // insert abc
8181 // insert xyz
8182 //
8183 // With a newline at the end which makes the split think that there are
8184 // three lines.
8185 //
8186 // If a session was presented (eg: a bug), then the response would look
8187 // like;
8188 // insert abc
8189 // lookup abc
8190 // insert xyz
8191
8192 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008193 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248194 }
8195}
8196
[email protected]dffe8242012-03-20 15:14:278197// This the fingerprint of the "Testing CA" certificate used by the testserver.
8198// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268199static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278200 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8201 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8202
[email protected]51523f52013-07-31 21:57:288203// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8204// testserver.
8205static const SHA256HashValue kOCSPTestCertSPKI = { {
8206 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8207 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8208 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8209 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8210} };
8211
[email protected]dffe8242012-03-20 15:14:278212// This is the policy OID contained in the certificates that testserver
8213// generates.
8214static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8215
8216class HTTPSOCSPTest : public HTTPSRequestTest {
8217 public:
8218 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098219 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088220 ev_test_policy_(
8221 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8222 kOCSPTestCertFingerprint,
8223 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028224 }
8225
dcheng67be2b1f2014-10-27 21:47:298226 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098227 SetupContext(&context_);
8228 context_.Init();
[email protected]dffe8242012-03-20 15:14:278229
[email protected]cba24642014-08-15 20:49:598230 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208231 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428232 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508233 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278234
davidben71f35ff2015-04-17 20:54:488235#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098236 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278237 EnsureNSSHttpIOInit();
8238#endif
8239 }
8240
[email protected]ce7d0cbc2013-05-03 18:57:228241 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278242 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538243 // We always overwrite out_cert_status.
8244 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228245 SpawnedTestServer test_server(
8246 SpawnedTestServer::TYPE_HTTPS,
8247 ssl_options,
8248 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278249 ASSERT_TRUE(test_server.Start());
8250
8251 TestDelegate d;
8252 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:198253 scoped_ptr<URLRequest> r(context_.CreateRequest(
davidben151423e2015-03-23 18:48:368254 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198255 r->Start();
[email protected]dffe8242012-03-20 15:14:278256
[email protected]255620da2013-08-19 13:14:298257 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278258
8259 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198260 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278261 }
8262
dcheng67be2b1f2014-10-27 21:47:298263 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488264#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278265 ShutdownNSSHttpIO();
8266#endif
8267 }
8268
[email protected]a13234c2012-03-20 21:45:028269 protected:
8270 // SetupContext configures the URLRequestContext that will be used for making
8271 // connetions to testserver. This can be overridden in test subclasses for
8272 // different behaviour.
8273 virtual void SetupContext(URLRequestContext* context) {
8274 context->set_ssl_config_service(
8275 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208276 true /* online revocation checking */,
8277 false /* require rev. checking for local
8278 anchors */));
[email protected]a13234c2012-03-20 21:45:028279 }
8280
[email protected]dffe8242012-03-20 15:14:278281 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098282 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088283 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278284};
8285
[email protected]a13234c2012-03-20 21:45:028286static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018287#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028288 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8289 // have that ability on other platforms.
8290 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8291#else
8292 return 0;
8293#endif
8294}
8295
[email protected]3a86a712013-07-30 07:16:208296// SystemSupportsHardFailRevocationChecking returns true iff the current
8297// operating system supports revocation checking and can distinguish between
8298// situations where a given certificate lacks any revocation information (eg:
8299// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8300// revocation information cannot be obtained (eg: the CRL was unreachable).
8301// If it does not, then tests which rely on 'hard fail' behaviour should be
8302// skipped.
8303static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:488304#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:208305 return true;
8306#else
8307 return false;
8308#endif
8309}
8310
[email protected]a13234c2012-03-20 21:45:028311// SystemUsesChromiumEVMetadata returns true iff the current operating system
8312// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8313// several tests are effected because our testing EV certificate won't be
8314// recognised as EV.
8315static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328316#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578317 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8318 return false;
[email protected]e1b2d732014-03-28 16:20:328319#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8320 // On OS X and Android, we use the system to tell us whether a certificate is
8321 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018322 return false;
8323#else
8324 return true;
8325#endif
8326}
8327
[email protected]b6f2de32012-08-17 04:35:088328static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008329#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578330 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8331 return false;
8332#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028333 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8334#elif defined(OS_ANDROID)
8335 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8336 return false;
8337#else
8338 return true;
8339#endif
8340}
8341
davidbend1fb2f12014-11-08 02:51:008342static bool SystemSupportsOCSPStapling() {
davidben71f35ff2015-04-17 20:54:488343#if defined(USE_NSS_CERTS)
davidbend1fb2f12014-11-08 02:51:008344 return true;
8345#elif defined(OS_WIN)
8346 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8347#else
8348 return false;
8349#endif
8350}
8351
[email protected]dffe8242012-03-20 15:14:278352TEST_F(HTTPSOCSPTest, Valid) {
8353 if (!SystemSupportsOCSP()) {
8354 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8355 return;
8356 }
8357
[email protected]ce7d0cbc2013-05-03 18:57:228358 SpawnedTestServer::SSLOptions ssl_options(
8359 SpawnedTestServer::SSLOptions::CERT_AUTO);
8360 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278361
[email protected]924e9f92012-12-16 22:00:538362 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128363 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278364
8365 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8366
[email protected]a13234c2012-03-20 21:45:028367 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8368 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278369
8370 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8371}
8372
8373TEST_F(HTTPSOCSPTest, Revoked) {
8374 if (!SystemSupportsOCSP()) {
8375 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8376 return;
8377 }
8378
[email protected]ce7d0cbc2013-05-03 18:57:228379 SpawnedTestServer::SSLOptions ssl_options(
8380 SpawnedTestServer::SSLOptions::CERT_AUTO);
8381 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278382
8383 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128384 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278385
[email protected]a592c0432012-12-01 18:10:298386#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278387 // Doesn't pass on OS X yet for reasons that need to be investigated.
8388 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8389#endif
8390 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8391 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8392}
8393
8394TEST_F(HTTPSOCSPTest, Invalid) {
8395 if (!SystemSupportsOCSP()) {
8396 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8397 return;
8398 }
8399
[email protected]ce7d0cbc2013-05-03 18:57:228400 SpawnedTestServer::SSLOptions ssl_options(
8401 SpawnedTestServer::SSLOptions::CERT_AUTO);
8402 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:278403
[email protected]924e9f92012-12-16 22:00:538404 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128405 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278406
[email protected]a13234c2012-03-20 21:45:028407 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278408 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:278409
8410 // Without a positive OCSP response, we shouldn't show the EV status.
8411 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8412 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8413}
[email protected]a13234c2012-03-20 21:45:028414
davidbend1fb2f12014-11-08 02:51:008415TEST_F(HTTPSOCSPTest, ValidStapled) {
8416 if (!SystemSupportsOCSPStapling()) {
8417 LOG(WARNING)
8418 << "Skipping test because system doesn't support OCSP stapling";
8419 return;
8420 }
8421
8422 SpawnedTestServer::SSLOptions ssl_options(
8423 SpawnedTestServer::SSLOptions::CERT_AUTO);
8424 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8425 ssl_options.staple_ocsp_response = true;
8426 ssl_options.ocsp_server_unavailable = true;
8427
8428 CertStatus cert_status;
8429 DoConnection(ssl_options, &cert_status);
8430
8431 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8432
8433 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8434 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8435
8436 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8437}
8438
davidben6c3191b2014-11-21 22:38:048439// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:488440#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:048441#define MAYBE_RevokedStapled DISABLED_RevokedStapled
8442#else
8443#define MAYBE_RevokedStapled RevokedStapled
8444#endif
8445TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
davidbend1fb2f12014-11-08 02:51:008446 if (!SystemSupportsOCSPStapling()) {
8447 LOG(WARNING)
8448 << "Skipping test because system doesn't support OCSP stapling";
8449 return;
8450 }
8451
8452 SpawnedTestServer::SSLOptions ssl_options(
8453 SpawnedTestServer::SSLOptions::CERT_AUTO);
8454 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8455 ssl_options.staple_ocsp_response = true;
8456 ssl_options.ocsp_server_unavailable = true;
8457
8458 CertStatus cert_status;
8459 DoConnection(ssl_options, &cert_status);
8460
8461 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8462 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8463 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8464}
8465
[email protected]3a86a712013-07-30 07:16:208466class HTTPSHardFailTest : public HTTPSOCSPTest {
8467 protected:
dchengb03027d2014-10-21 12:00:208468 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:208469 context->set_ssl_config_service(
8470 new TestSSLConfigService(false /* check for EV */,
8471 false /* online revocation checking */,
8472 true /* require rev. checking for local
8473 anchors */));
8474 }
8475};
8476
[email protected]3a86a712013-07-30 07:16:208477TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8478 if (!SystemSupportsOCSP()) {
8479 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8480 return;
8481 }
8482
8483 if (!SystemSupportsHardFailRevocationChecking()) {
8484 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8485 << "revocation checking";
8486 return;
8487 }
8488
8489 SpawnedTestServer::SSLOptions ssl_options(
8490 SpawnedTestServer::SSLOptions::CERT_AUTO);
8491 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8492
8493 CertStatus cert_status;
8494 DoConnection(ssl_options, &cert_status);
8495
8496 EXPECT_EQ(CERT_STATUS_REVOKED,
8497 cert_status & CERT_STATUS_REVOKED);
8498
8499 // Without a positive OCSP response, we shouldn't show the EV status.
8500 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8501}
8502
[email protected]a13234c2012-03-20 21:45:028503class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8504 protected:
dchengb03027d2014-10-21 12:00:208505 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028506 context->set_ssl_config_service(
8507 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208508 false /* online revocation checking */,
8509 false /* require rev. checking for local
8510 anchors */));
[email protected]a13234c2012-03-20 21:45:028511 }
8512};
8513
8514TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8515 if (!SystemSupportsOCSP()) {
8516 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8517 return;
8518 }
8519
[email protected]ce7d0cbc2013-05-03 18:57:228520 SpawnedTestServer::SSLOptions ssl_options(
8521 SpawnedTestServer::SSLOptions::CERT_AUTO);
8522 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028523 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8524
[email protected]924e9f92012-12-16 22:00:538525 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128526 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028527
8528 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8529 cert_status & CERT_STATUS_ALL_ERRORS);
8530
8531 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088532 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8533 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028534}
8535
[email protected]be0fff62013-08-29 23:37:488536TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8537 if (!SystemSupportsOCSP()) {
8538 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8539 return;
8540 }
8541
8542 SpawnedTestServer::SSLOptions ssl_options(
8543 SpawnedTestServer::SSLOptions::CERT_AUTO);
8544 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8545 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8546
8547 CertStatus cert_status;
8548 DoConnection(ssl_options, &cert_status);
8549
8550 // Currently only works for Windows. When using NSS or OS X, it's not
8551 // possible to determine whether the check failed because of actual
8552 // revocation or because there was an OCSP failure.
8553#if defined(OS_WIN)
8554 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8555#else
8556 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8557#endif
8558
8559 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8560 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8561 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8562}
8563
[email protected]a13234c2012-03-20 21:45:028564TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8565 if (!SystemSupportsOCSP()) {
8566 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8567 return;
8568 }
8569
[email protected]ce7d0cbc2013-05-03 18:57:228570 SpawnedTestServer::SSLOptions ssl_options(
8571 SpawnedTestServer::SSLOptions::CERT_AUTO);
8572 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:028573 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8574
8575 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128576 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028577
8578 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8579
8580 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8581 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:088582 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8583 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028584}
8585
8586TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8587 if (!SystemSupportsOCSP()) {
8588 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8589 return;
8590 }
8591
[email protected]ce7d0cbc2013-05-03 18:57:228592 SpawnedTestServer::SSLOptions ssl_options(
8593 SpawnedTestServer::SSLOptions::CERT_AUTO);
8594 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028595 SSLConfigService::SetCRLSet(
8596 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8597
8598 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128599 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028600
8601 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8602 cert_status & CERT_STATUS_ALL_ERRORS);
8603
8604 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088605 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8606 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028607}
8608
[email protected]51523f52013-07-31 21:57:288609TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8610 if (!SystemSupportsOCSP()) {
8611 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8612 return;
8613 }
8614
8615 SpawnedTestServer::SSLOptions ssl_options(
8616 SpawnedTestServer::SSLOptions::CERT_AUTO);
8617 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8618 SSLConfigService::SetCRLSet(
8619 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8620 false, &kOCSPTestCertSPKI, "")));
8621
8622 CertStatus cert_status;
8623 DoConnection(ssl_options, &cert_status);
8624
8625 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8626 // revocation check for EV.
8627 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8628 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8629 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8630 EXPECT_FALSE(
8631 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8632}
8633
8634TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8635 if (!SystemSupportsOCSP()) {
8636 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8637 return;
8638 }
8639
[email protected]ce7d0cbc2013-05-03 18:57:228640 SpawnedTestServer::SSLOptions ssl_options(
8641 SpawnedTestServer::SSLOptions::CERT_AUTO);
8642 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028643 SSLConfigService::SetCRLSet(
8644 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8645
[email protected]51523f52013-07-31 21:57:288646 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:128647 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028648
[email protected]51523f52013-07-31 21:57:288649 // Even with a fresh CRLSet, we should still do online revocation checks when
8650 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8651 // test.
8652 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8653 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:028654
[email protected]51523f52013-07-31 21:57:288655 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:028656 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:288657 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028658}
8659
[email protected]b6f2de32012-08-17 04:35:088660TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8661 // Test that when EV verification is requested, but online revocation
8662 // checking is disabled, and the leaf certificate is not in fact EV, that
8663 // no revocation checking actually happens.
8664 if (!SystemSupportsOCSP()) {
8665 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8666 return;
8667 }
8668
8669 // Unmark the certificate's OID as EV, which should disable revocation
8670 // checking (as per the user preference)
8671 ev_test_policy_.reset();
8672
[email protected]ce7d0cbc2013-05-03 18:57:228673 SpawnedTestServer::SSLOptions ssl_options(
8674 SpawnedTestServer::SSLOptions::CERT_AUTO);
8675 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:088676 SSLConfigService::SetCRLSet(
8677 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8678
8679 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128680 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:088681
8682 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8683
8684 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8685 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8686}
8687
[email protected]a13234c2012-03-20 21:45:028688class HTTPSCRLSetTest : public HTTPSOCSPTest {
8689 protected:
dchengb03027d2014-10-21 12:00:208690 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028691 context->set_ssl_config_service(
8692 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208693 false /* online revocation checking */,
8694 false /* require rev. checking for local
8695 anchors */));
[email protected]a13234c2012-03-20 21:45:028696 }
8697};
8698
8699TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:228700 SpawnedTestServer::SSLOptions ssl_options(
8701 SpawnedTestServer::SSLOptions::CERT_AUTO);
8702 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028703 SSLConfigService::SetCRLSet(
8704 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8705
[email protected]924e9f92012-12-16 22:00:538706 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128707 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028708
8709 // If we're not trying EV verification then, even if the CRLSet has expired,
8710 // we don't fall back to online revocation checks.
8711 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8712 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8713 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8714}
[email protected]51523f52013-07-31 21:57:288715
8716TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:308717#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:288718 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8719 return;
8720#endif
8721
8722 SpawnedTestServer::SSLOptions ssl_options(
8723 SpawnedTestServer::SSLOptions::CERT_AUTO);
8724 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8725 ssl_options.cert_serial = 10;
8726 SSLConfigService::SetCRLSet(
8727 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8728 false, &kOCSPTestCertSPKI, "\x0a")));
8729
8730 CertStatus cert_status = 0;
8731 DoConnection(ssl_options, &cert_status);
8732
8733 // If the certificate is recorded as revoked in the CRLSet, that should be
8734 // reflected without online revocation checking.
8735 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8736 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8737 EXPECT_FALSE(
8738 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8739}
[email protected]316c1e5e2012-09-12 15:17:448740#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278741
[email protected]316c1e5e2012-09-12 15:17:448742#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:318743class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:118744 public:
[email protected]d9fca99a2012-02-24 16:16:208745 URLRequestTestFTP()
[email protected]ce7d0cbc2013-05-03 18:57:228746 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:158747 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:118748 }
8749
[email protected]b89ca032009-08-31 21:41:318750 protected:
[email protected]ce7d0cbc2013-05-03 18:57:228751 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:318752};
8753
[email protected]d2a133182012-08-05 16:44:088754// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:098755TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:088756 ASSERT_TRUE(test_server_.Start());
8757
[email protected]9d5730b2012-08-24 17:42:498758 URLRequestJobFactoryImpl job_factory;
[email protected]e0f35c92013-05-08 16:04:348759 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
[email protected]d2a133182012-08-05 16:44:088760
8761 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:088762 job_factory.SetProtocolHandler(
8763 "ftp",
[email protected]e0f35c92013-05-08 16:04:348764 new FtpProtocolHandler(&ftp_transaction_factory));
[email protected]d2a133182012-08-05 16:44:088765 default_context_.set_job_factory(&job_factory);
8766
8767 TestDelegate d;
8768 {
davidben151423e2015-03-23 18:48:368769 scoped_ptr<URLRequest> r(
8770 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198771 r->Start();
8772 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:088773
[email protected]255620da2013-08-19 13:14:298774 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:088775
[email protected]f7022f32014-08-21 16:32:198776 EXPECT_FALSE(r->is_pending());
8777 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8778 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:088779 }
8780}
8781
[email protected]5accf7332009-11-24 03:41:388782// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128783TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:118784 ASSERT_TRUE(test_server_.Start());
8785
[email protected]a25e90e2009-09-09 17:05:378786 TestDelegate d;
8787 {
[email protected]f7022f32014-08-21 16:32:198788 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368789 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198790 r->Start();
8791 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378792
[email protected]255620da2013-08-19 13:14:298793 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:378794
[email protected]f7022f32014-08-21 16:32:198795 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378796 EXPECT_EQ(1, d.response_started_count());
8797 EXPECT_FALSE(d.received_data_before_response());
8798 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:198799 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198800 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198801 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198802 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:378803 }
8804}
8805
[email protected]7df70012010-02-04 00:09:558806// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128807TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:118808 ASSERT_TRUE(test_server_.Start());
8809
[email protected]6cdfd7f2013-02-08 20:40:158810 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278811 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028812 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278813 TestDelegate d;
8814 {
[email protected]f7022f32014-08-21 16:32:198815 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368816 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198817 r->Start();
8818 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278819
[email protected]255620da2013-08-19 13:14:298820 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278821
8822 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498823 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278824
[email protected]f7022f32014-08-21 16:32:198825 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278826 EXPECT_EQ(1, d.response_started_count());
8827 EXPECT_FALSE(d.received_data_before_response());
8828 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:198829 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198830 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198831 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198832 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278833 }
8834}
8835
[email protected]e9ecbd12009-12-20 18:44:408836// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128837TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:118838 ASSERT_TRUE(test_server_.Start());
8839
[email protected]6cdfd7f2013-02-08 20:40:158840 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278841 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028842 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278843 TestDelegate d;
8844 {
[email protected]f7022f32014-08-21 16:32:198845 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]95409e12010-08-17 20:07:118846 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
davidben151423e2015-03-23 18:48:368847 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198848 r->Start();
8849 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278850
[email protected]255620da2013-08-19 13:14:298851 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278852
8853 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498854 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278855
[email protected]f7022f32014-08-21 16:32:198856 EXPECT_FALSE(r->is_pending());
[email protected]6d81b482011-02-22 19:47:198857 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198858 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198859 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198860 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278861 EXPECT_EQ(1, d.response_started_count());
8862 EXPECT_FALSE(d.received_data_before_response());
8863 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:258864
8865 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198866 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258867 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:278868 }
8869}
8870
[email protected]49abd652010-08-05 05:04:538871// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128872TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:118873 ASSERT_TRUE(test_server_.Start());
8874
[email protected]6cdfd7f2013-02-08 20:40:158875 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278876 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028877 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278878 TestDelegate d;
8879 {
[email protected]f7022f32014-08-21 16:32:198880 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8881 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8882 "wrong_password"),
davidben151423e2015-03-23 18:48:368883 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198884 r->Start();
8885 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278886
[email protected]255620da2013-08-19 13:14:298887 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278888
8889 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498890 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278891
[email protected]f7022f32014-08-21 16:32:198892 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278893 EXPECT_EQ(1, d.response_started_count());
8894 EXPECT_FALSE(d.received_data_before_response());
8895 EXPECT_EQ(d.bytes_received(), 0);
8896 }
8897}
8898
[email protected]cde4e80d2009-10-16 19:58:158899// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128900TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:118901 ASSERT_TRUE(test_server_.Start());
8902
[email protected]6cdfd7f2013-02-08 20:40:158903 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:588904 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8905 app_path = app_path.AppendASCII("LICENSE");
8906 TestDelegate d;
8907 // Set correct login credentials. The delegate will be asked for them when
8908 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588909 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:588910 {
[email protected]f7022f32014-08-21 16:32:198911 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8912 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8913 "wrong_password"),
davidben151423e2015-03-23 18:48:368914 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198915 r->Start();
8916 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588917
[email protected]255620da2013-08-19 13:14:298918 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:588919
8920 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498921 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:588922
[email protected]f7022f32014-08-21 16:32:198923 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588924 EXPECT_EQ(1, d.response_started_count());
8925 EXPECT_FALSE(d.received_data_before_response());
8926 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8927 }
8928}
8929
[email protected]49abd652010-08-05 05:04:538930// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128931TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:118932 ASSERT_TRUE(test_server_.Start());
8933
[email protected]6cdfd7f2013-02-08 20:40:158934 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278935 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028936 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278937 TestDelegate d;
8938 {
davidben151423e2015-03-23 18:48:368939 scoped_ptr<URLRequest> r(
8940 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
8941 "/LICENSE", "wrong_user", "chrome"),
8942 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198943 r->Start();
8944 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278945
[email protected]255620da2013-08-19 13:14:298946 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278947
8948 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498949 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278950
[email protected]f7022f32014-08-21 16:32:198951 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278952 EXPECT_EQ(1, d.response_started_count());
8953 EXPECT_FALSE(d.received_data_before_response());
8954 EXPECT_EQ(d.bytes_received(), 0);
8955 }
8956}
[email protected]8b8a197d2009-08-26 15:57:588957
[email protected]cde4e80d2009-10-16 19:58:158958// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128959TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:118960 ASSERT_TRUE(test_server_.Start());
8961
[email protected]6cdfd7f2013-02-08 20:40:158962 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:588963 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8964 app_path = app_path.AppendASCII("LICENSE");
8965 TestDelegate d;
8966 // Set correct login credentials. The delegate will be asked for them when
8967 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588968 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:588969 {
davidben151423e2015-03-23 18:48:368970 scoped_ptr<URLRequest> r(
8971 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
8972 "/LICENSE", "wrong_user", "chrome"),
8973 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198974 r->Start();
8975 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588976
[email protected]255620da2013-08-19 13:14:298977 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:588978
8979 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498980 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:588981
[email protected]f7022f32014-08-21 16:32:198982 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588983 EXPECT_EQ(1, d.response_started_count());
8984 EXPECT_FALSE(d.received_data_before_response());
8985 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8986 }
8987}
[email protected]60a3df52009-09-22 16:13:248988
[email protected]cde4e80d2009-10-16 19:58:158989// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128990TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:118991 ASSERT_TRUE(test_server_.Start());
8992
[email protected]6cdfd7f2013-02-08 20:40:158993 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:248994 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8995 app_path = app_path.AppendASCII("LICENSE");
8996
8997 scoped_ptr<TestDelegate> d(new TestDelegate);
8998 {
8999 // Pass correct login identity in the URL.
[email protected]f7022f32014-08-21 16:32:199000 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:199001 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
davidben151423e2015-03-23 18:48:369002 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199003 r->Start();
9004 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249005
[email protected]255620da2013-08-19 13:14:299006 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249007
9008 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499009 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249010
[email protected]f7022f32014-08-21 16:32:199011 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249012 EXPECT_EQ(1, d->response_started_count());
9013 EXPECT_FALSE(d->received_data_before_response());
9014 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9015 }
9016
9017 d.reset(new TestDelegate);
9018 {
9019 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199020 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369021 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199022 r->Start();
9023 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249024
[email protected]255620da2013-08-19 13:14:299025 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249026
9027 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499028 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249029
[email protected]f7022f32014-08-21 16:32:199030 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249031 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]cde4e80d2009-10-16 19:58:159037// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:129038TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[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]60a3df52009-09-22 16:13:249042 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
9043 app_path = app_path.AppendASCII("LICENSE");
9044
9045 scoped_ptr<TestDelegate> d(new TestDelegate);
9046 // Set correct login credentials. The delegate will be asked for them when
9047 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589048 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249049 {
[email protected]f7022f32014-08-21 16:32:199050 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9051 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
9052 "wrong_password"),
davidben151423e2015-03-23 18:48:369053 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199054 r->Start();
9055 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249056
[email protected]255620da2013-08-19 13:14:299057 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249058
9059 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499060 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249061
[email protected]f7022f32014-08-21 16:32:199062 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249063 EXPECT_EQ(1, d->response_started_count());
9064 EXPECT_FALSE(d->received_data_before_response());
9065 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9066 }
9067
9068 // Use a new delegate without explicit credentials. The cached ones should be
9069 // used.
9070 d.reset(new TestDelegate);
9071 {
9072 // Don't pass wrong credentials in the URL, they would override valid cached
9073 // ones.
[email protected]f7022f32014-08-21 16:32:199074 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369075 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199076 r->Start();
9077 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249078
[email protected]255620da2013-08-19 13:14:299079 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249080
9081 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499082 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249083
[email protected]f7022f32014-08-21 16:32:199084 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249085 EXPECT_EQ(1, d->response_started_count());
9086 EXPECT_FALSE(d->received_data_before_response());
9087 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9088 }
9089}
[email protected]316c1e5e2012-09-12 15:17:449090#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519091
9092} // namespace net