blob: fd9a6504cedd1b9f90aea0897ac14ad0dd2c1a81 [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
ttuttlec0c828492015-05-15 01:25:556826TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
6827 ASSERT_TRUE(test_server_.Start());
6828
6829 TestDelegate d;
6830 GURL test_url(test_server_.GetURL(std::string()));
6831 scoped_ptr<URLRequest> req(
6832 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
6833
6834 req->Start();
6835 base::RunLoop().Run();
6836
6837 EXPECT_TRUE(req->response_info().network_accessed);
6838}
6839
6840TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
6841 ASSERT_TRUE(test_server_.Start());
6842
6843 // Populate the cache.
6844 TestDelegate d;
6845 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6846 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
6847 req->Start();
6848 base::RunLoop().Run();
6849
6850 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6851 EXPECT_TRUE(req->response_info().network_accessed);
6852 EXPECT_FALSE(req->response_info().was_cached);
6853
6854 req = default_context_.CreateRequest(test_server_.GetURL("cachetime"),
6855 DEFAULT_PRIORITY, &d);
6856 req->Start();
6857 base::RunLoop().Run();
6858
6859 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6860 EXPECT_FALSE(req->response_info().network_accessed);
6861 EXPECT_TRUE(req->response_info().was_cached);
6862}
6863
6864TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
6865 ASSERT_TRUE(test_server_.Start());
6866
6867 TestDelegate d;
6868 GURL test_url(test_server_.GetURL(std::string()));
6869 scoped_ptr<URLRequest> req(
6870 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
6871 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
6872
6873 req->Start();
6874 base::RunLoop().Run();
6875
6876 EXPECT_FALSE(req->response_info().network_accessed);
6877}
6878
bengr1bf8e942014-11-07 01:36:506879class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
6880 public:
6881 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
6882 // ideally remove the dependency on URLRequestTestJob, and maybe move these
6883 // tests into the factory tests.
6884 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
6885 }
6886
6887 void SetUpFactory() override {
6888 interceptor_ = new MockURLRequestInterceptor();
6889 job_factory_.reset(new URLRequestInterceptingJobFactory(
6890 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
6891 }
6892
6893 MockURLRequestInterceptor* interceptor() const {
6894 return interceptor_;
6895 }
6896
6897 private:
6898 MockURLRequestInterceptor* interceptor_;
6899};
6900
6901TEST_F(URLRequestInterceptorTestHTTP,
6902 NetworkDelegateNotificationOnRedirectIntercept) {
6903 interceptor()->set_intercept_redirect(true);
6904 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
6905 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
6906
6907 ASSERT_TRUE(test_server()->Start());
6908
6909 TestDelegate d;
6910 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:366911 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:506912 req->Start();
6913 base::RunLoop().Run();
6914
6915 EXPECT_TRUE(interceptor()->did_intercept_redirect());
6916 // Check we got one good response
6917 EXPECT_TRUE(req->status().is_success());
6918 if (req->status().is_success())
6919 EXPECT_EQ(200, req->response_headers()->response_code());
6920
6921 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6922 EXPECT_EQ(1, d.response_started_count());
6923 EXPECT_EQ(0, d.received_redirect_count());
6924
6925 EXPECT_EQ(1, default_network_delegate()->created_requests());
6926 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6927 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
6928}
6929
6930TEST_F(URLRequestInterceptorTestHTTP,
6931 NetworkDelegateNotificationOnErrorIntercept) {
6932 // Intercept that error and respond with an OK response.
6933 interceptor()->set_intercept_final_response(true);
6934 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
6935 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
6936 default_network_delegate()->set_can_be_intercepted_on_error(true);
6937
6938 ASSERT_TRUE(test_server()->Start());
6939
6940 TestDelegate d;
6941 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6942 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366943 &d));
bengr1bf8e942014-11-07 01:36:506944 req->set_method("GET");
6945 req->Start();
6946 base::RunLoop().Run();
6947
6948 EXPECT_TRUE(interceptor()->did_intercept_final());
6949
6950 // Check we received one good response.
6951 EXPECT_TRUE(req->status().is_success());
6952 if (req->status().is_success())
6953 EXPECT_EQ(200, req->response_headers()->response_code());
6954 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6955 EXPECT_EQ(1, d.response_started_count());
6956 EXPECT_EQ(0, d.received_redirect_count());
6957
6958 EXPECT_EQ(1, default_network_delegate()->created_requests());
6959 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6960 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
6961}
6962
6963TEST_F(URLRequestInterceptorTestHTTP,
6964 NetworkDelegateNotificationOnResponseIntercept) {
6965 // Intercept that error and respond with an OK response.
6966 interceptor()->set_intercept_final_response(true);
6967
6968 // Intercept with a real URLRequestHttpJob.
6969 interceptor()->set_use_url_request_http_job(true);
6970
6971 ASSERT_TRUE(test_server()->Start());
6972
6973 TestDelegate d;
6974 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:366975 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:506976 req->set_method("GET");
6977 req->Start();
6978 base::RunLoop().Run();
6979
6980 EXPECT_TRUE(interceptor()->did_intercept_final());
6981
6982 // Check we received one good response.
6983 EXPECT_TRUE(req->status().is_success());
6984 if (req->status().is_success())
6985 EXPECT_EQ(200, req->response_headers()->response_code());
6986 EXPECT_EQ("hello", d.data_received());
6987 EXPECT_EQ(1, d.response_started_count());
6988 EXPECT_EQ(0, d.received_redirect_count());
6989
6990 EXPECT_EQ(1, default_network_delegate()->created_requests());
6991 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
6992 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
6993}
6994
mkwst0c5eab872014-11-21 14:18:546995class URLRequestTestReferrerPolicy : public URLRequestTest {
6996 public:
6997 URLRequestTestReferrerPolicy() {}
6998
6999 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
7000 origin_server_.reset(new SpawnedTestServer(
7001 origin_type, SpawnedTestServer::kLocalhost,
7002 origin_type == SpawnedTestServer::TYPE_HTTPS
7003 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
7004 : base::FilePath(
7005 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
7006 ASSERT_TRUE(origin_server_->Start());
7007 }
7008
7009 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
7010 SpawnedTestServer::Type destination_type) {
7011 origin_server_.reset(new SpawnedTestServer(
7012 origin_type, SpawnedTestServer::kLocalhost,
7013 origin_type == SpawnedTestServer::TYPE_HTTPS
7014 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
7015 : base::FilePath(
7016 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
7017 ASSERT_TRUE(origin_server_->Start());
7018
7019 destination_server_.reset(new SpawnedTestServer(
7020 destination_type, SpawnedTestServer::kLocalhost,
7021 destination_type == SpawnedTestServer::TYPE_HTTPS
7022 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
7023 : base::FilePath(
7024 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
7025 ASSERT_TRUE(destination_server_->Start());
7026 }
7027
7028 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7029 const GURL& referrer,
7030 const GURL& expected) {
7031 // Create and execute the request: we'll only have a |destination_server_|
7032 // if the origins are meant to be distinct. Otherwise, we'll use the
7033 // |origin_server_| for both endpoints.
7034 GURL destination_url =
7035 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
7036 : origin_server_->GetURL("echoheader?Referer");
7037 GURL origin_url =
7038 origin_server_->GetURL("server-redirect?" + destination_url.spec());
7039
7040 TestDelegate d;
7041 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367042 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547043 req->set_referrer_policy(policy);
7044 req->SetReferrer(referrer.spec());
7045 req->Start();
7046 base::RunLoop().Run();
7047
7048 EXPECT_EQ(1, d.response_started_count());
7049 EXPECT_EQ(1, d.received_redirect_count());
7050 EXPECT_EQ(destination_url, req->url());
7051 EXPECT_TRUE(req->status().is_success());
7052 EXPECT_EQ(200, req->response_headers()->response_code());
7053
7054 EXPECT_EQ(expected.spec(), req->referrer());
7055 if (expected.is_empty())
7056 EXPECT_EQ("None", d.data_received());
7057 else
7058 EXPECT_EQ(expected.spec(), d.data_received());
7059 }
7060
7061 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
7062
7063 private:
7064 scoped_ptr<SpawnedTestServer> origin_server_;
7065 scoped_ptr<SpawnedTestServer> destination_server_;
7066};
7067
7068TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
7069 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
7070
7071 VerifyReferrerAfterRedirect(
7072 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7073 origin_server()->GetURL("path/to/file.html"),
7074 origin_server()->GetURL("path/to/file.html"));
7075
7076 VerifyReferrerAfterRedirect(
7077 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7078 origin_server()->GetURL("path/to/file.html"),
7079 origin_server()->GetURL("path/to/file.html"));
7080
7081 VerifyReferrerAfterRedirect(
7082 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7083 origin_server()->GetURL("path/to/file.html"),
7084 origin_server()->GetURL("path/to/file.html"));
7085
7086 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7087 origin_server()->GetURL("path/to/file.html"),
7088 origin_server()->GetURL("path/to/file.html"));
7089}
7090
7091TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
7092 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7093 SpawnedTestServer::TYPE_HTTP);
7094
7095 VerifyReferrerAfterRedirect(
7096 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7097 origin_server()->GetURL("path/to/file.html"),
7098 origin_server()->GetURL("path/to/file.html"));
7099
7100 VerifyReferrerAfterRedirect(
7101 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7102 origin_server()->GetURL("path/to/file.html"),
7103 origin_server()->GetURL(std::string()));
7104
7105 VerifyReferrerAfterRedirect(
7106 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7107 origin_server()->GetURL("path/to/file.html"),
7108 origin_server()->GetURL(std::string()));
7109
7110 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7111 origin_server()->GetURL("path/to/file.html"),
7112 origin_server()->GetURL("path/to/file.html"));
7113}
7114
7115TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
7116 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
7117
7118 VerifyReferrerAfterRedirect(
7119 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7120 origin_server()->GetURL("path/to/file.html"),
7121 origin_server()->GetURL("path/to/file.html"));
7122
7123 VerifyReferrerAfterRedirect(
7124 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7125 origin_server()->GetURL("path/to/file.html"),
7126 origin_server()->GetURL("path/to/file.html"));
7127
7128 VerifyReferrerAfterRedirect(
7129 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7130 origin_server()->GetURL("path/to/file.html"),
7131 origin_server()->GetURL("path/to/file.html"));
7132
7133 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7134 origin_server()->GetURL("path/to/file.html"),
7135 origin_server()->GetURL("path/to/file.html"));
7136}
7137
7138TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7139 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7140 SpawnedTestServer::TYPE_HTTPS);
7141
7142 VerifyReferrerAfterRedirect(
7143 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7144 origin_server()->GetURL("path/to/file.html"),
7145 origin_server()->GetURL("path/to/file.html"));
7146
7147 VerifyReferrerAfterRedirect(
7148 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7149 origin_server()->GetURL("path/to/file.html"),
7150 origin_server()->GetURL(std::string()));
7151
7152 VerifyReferrerAfterRedirect(
7153 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7154 origin_server()->GetURL("path/to/file.html"),
7155 origin_server()->GetURL(std::string()));
7156
7157 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7158 origin_server()->GetURL("path/to/file.html"),
7159 origin_server()->GetURL("path/to/file.html"));
7160}
7161
7162TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7163 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7164 SpawnedTestServer::TYPE_HTTPS);
7165
7166 VerifyReferrerAfterRedirect(
7167 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7168 origin_server()->GetURL("path/to/file.html"),
7169 origin_server()->GetURL("path/to/file.html"));
7170
7171 VerifyReferrerAfterRedirect(
7172 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7173 origin_server()->GetURL("path/to/file.html"),
7174 origin_server()->GetURL(std::string()));
7175
7176 VerifyReferrerAfterRedirect(
7177 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7178 origin_server()->GetURL("path/to/file.html"),
7179 origin_server()->GetURL(std::string()));
7180
7181 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7182 origin_server()->GetURL("path/to/file.html"),
7183 origin_server()->GetURL("path/to/file.html"));
7184}
7185
7186TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7187 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7188 SpawnedTestServer::TYPE_HTTP);
7189
7190 VerifyReferrerAfterRedirect(
7191 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7192 origin_server()->GetURL("path/to/file.html"), GURL());
7193
7194 VerifyReferrerAfterRedirect(
7195 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7196 origin_server()->GetURL("path/to/file.html"), GURL());
7197
7198 VerifyReferrerAfterRedirect(
7199 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7200 origin_server()->GetURL("path/to/file.html"),
7201 origin_server()->GetURL(std::string()));
7202
7203 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7204 origin_server()->GetURL("path/to/file.html"),
7205 origin_server()->GetURL("path/to/file.html"));
7206}
7207
[email protected]73e0bba2009-02-19 22:57:097208class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507209 public:
[email protected]ef2bf422012-05-11 03:27:097210 HTTPSRequestTest() : default_context_(true) {
7211 default_context_.set_network_delegate(&default_network_delegate_);
7212 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507213 }
dcheng67be2b1f2014-10-27 21:47:297214 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507215
7216 protected:
[email protected]ceefd7fd2012-11-29 00:36:247217 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097218 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467219};
7220
[email protected]c044616e2013-02-20 02:01:267221TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227222 SpawnedTestServer test_server(
7223 SpawnedTestServer::TYPE_HTTPS,
7224 SpawnedTestServer::kLocalhost,
7225 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117226 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467227
[email protected]ea224582008-12-07 20:25:467228 TestDelegate d;
7229 {
[email protected]f7022f32014-08-21 16:32:197230 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367231 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197232 r->Start();
7233 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467234
[email protected]255620da2013-08-19 13:14:297235 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467236
7237 EXPECT_EQ(1, d.response_started_count());
7238 EXPECT_FALSE(d.received_data_before_response());
7239 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197240 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197241 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197242 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197243 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197244 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467245 }
[email protected]ea224582008-12-07 20:25:467246}
7247
[email protected]5774ada2010-07-15 06:30:547248TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227249 SpawnedTestServer::SSLOptions ssl_options(
7250 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7251 SpawnedTestServer test_server(
7252 SpawnedTestServer::TYPE_HTTPS,
7253 ssl_options,
7254 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117255 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337256
7257 bool err_allowed = true;
7258 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7259 TestDelegate d;
7260 {
7261 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197262 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367263 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337264
[email protected]f7022f32014-08-21 16:32:197265 r->Start();
7266 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337267
[email protected]255620da2013-08-19 13:14:297268 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337269
7270 EXPECT_EQ(1, d.response_started_count());
7271 EXPECT_FALSE(d.received_data_before_response());
7272 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177273 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337274 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197275 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177276 } else {
[email protected]bacff652009-03-31 17:50:337277 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177278 }
[email protected]bacff652009-03-31 17:50:337279 }
7280 }
7281}
7282
[email protected]5774ada2010-07-15 06:30:547283TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227284 SpawnedTestServer::SSLOptions ssl_options(
7285 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7286 SpawnedTestServer test_server(
7287 SpawnedTestServer::TYPE_HTTPS,
7288 ssl_options,
7289 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117290 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337291
7292 // Iterate from false to true, just so that we do the opposite of the
7293 // previous test in order to increase test coverage.
7294 bool err_allowed = false;
7295 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7296 TestDelegate d;
7297 {
7298 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197299 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367300 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337301
[email protected]f7022f32014-08-21 16:32:197302 r->Start();
7303 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337304
[email protected]255620da2013-08-19 13:14:297305 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337306
7307 EXPECT_EQ(1, d.response_started_count());
7308 EXPECT_FALSE(d.received_data_before_response());
7309 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177310 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337311 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197312 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177313 } else {
[email protected]bacff652009-03-31 17:50:337314 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177315 }
[email protected]bacff652009-03-31 17:50:337316 }
7317 }
7318}
[email protected]73e0bba2009-02-19 22:57:097319
davidbena4c9d062015-04-03 22:34:257320// Tests that servers which require a deprecated cipher suite still work.
7321TEST_F(HTTPSRequestTest, CipherFallbackTest) {
vishal.b62985ca92015-04-17 08:45:517322 TestNetLog net_log;
davidbena4c9d062015-04-03 22:34:257323 default_context_.set_net_log(&net_log);
7324
7325 SpawnedTestServer::SSLOptions ssl_options;
7326 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
7327 SpawnedTestServer test_server(
7328 SpawnedTestServer::TYPE_HTTPS, ssl_options,
7329 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7330 ASSERT_TRUE(test_server.Start());
7331
7332 TestDelegate d;
7333 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7334 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7335 r->Start();
7336 EXPECT_TRUE(r->is_pending());
7337
7338 base::RunLoop().Run();
7339
7340 EXPECT_EQ(1, d.response_started_count());
7341 EXPECT_FALSE(d.received_data_before_response());
7342 EXPECT_NE(0, d.bytes_received());
7343 CheckSSLInfo(r->ssl_info());
7344 EXPECT_EQ(test_server.host_port_pair().host(), r->GetSocketAddress().host());
7345 EXPECT_EQ(test_server.host_port_pair().port(), r->GetSocketAddress().port());
7346
7347 // No version downgrade should have been necessary.
7348 EXPECT_FALSE(r->ssl_info().connection_status &
7349 SSL_CONNECTION_VERSION_FALLBACK);
7350 int expected_version = SSL_CONNECTION_VERSION_TLS1_2;
7351 if (SSLClientSocket::GetMaxSupportedSSLVersion() <
7352 SSL_PROTOCOL_VERSION_TLS1_2) {
7353 expected_version = SSL_CONNECTION_VERSION_TLS1_1;
7354 }
7355 EXPECT_EQ(expected_version,
7356 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
7357
mmenke43758e62015-05-04 21:09:467358 TestNetLogEntry::List entries;
davidbena4c9d062015-04-03 22:34:257359 net_log.GetEntries(&entries);
7360 ExpectLogContainsSomewhere(entries, 0, NetLog::TYPE_SSL_CIPHER_FALLBACK,
7361 NetLog::PHASE_NONE);
7362}
7363
[email protected]316c1e5e2012-09-12 15:17:447364// This tests that a load of www.google.com with a certificate error sets
7365// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7366// the interstitial to be fatal.
7367TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227368 SpawnedTestServer::SSLOptions ssl_options(
7369 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7370 SpawnedTestServer test_server(
7371 SpawnedTestServer::TYPE_HTTPS,
7372 ssl_options,
7373 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447374 ASSERT_TRUE(test_server.Start());
7375
7376 // We require that the URL be www.google.com in order to pick up the
7377 // preloaded HSTS entries in the TransportSecurityState. This means that we
7378 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247379 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447380
7381 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247382 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447383 TestURLRequestContext context(true);
7384 context.set_network_delegate(&network_delegate);
7385 context.set_host_resolver(&host_resolver);
7386 TransportSecurityState transport_security_state;
7387 context.set_transport_security_state(&transport_security_state);
7388 context.Init();
7389
7390 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197391 scoped_ptr<URLRequest> r(context.CreateRequest(
7392 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367393 test_server.host_port_pair().port())),
7394 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447395
[email protected]f7022f32014-08-21 16:32:197396 r->Start();
7397 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447398
[email protected]255620da2013-08-19 13:14:297399 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447400
7401 EXPECT_EQ(1, d.response_started_count());
7402 EXPECT_FALSE(d.received_data_before_response());
7403 EXPECT_TRUE(d.have_certificate_errors());
7404 EXPECT_TRUE(d.certificate_errors_are_fatal());
7405}
7406
7407// This tests that cached HTTPS page loads do not cause any updates to the
7408// TransportSecurityState.
7409TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7410 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7411 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227412 SpawnedTestServer::SSLOptions ssl_options(
7413 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7414 SpawnedTestServer test_server(
7415 SpawnedTestServer::TYPE_HTTPS,
7416 ssl_options,
7417 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447418 ASSERT_TRUE(test_server.Start());
7419
[email protected]9e6968d2014-05-07 21:46:267420 // We require that the URL be www.google.com in order to pick up the static
7421 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7422 // that we have to use a MockHostResolver in order to direct www.google.com to
7423 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447424
7425 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247426 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447427 TestURLRequestContext context(true);
7428 context.set_network_delegate(&network_delegate);
7429 context.set_host_resolver(&host_resolver);
7430 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267431
7432 TransportSecurityState::DomainState static_domain_state;
7433 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127434 "www.google.com", &static_domain_state));
[email protected]316c1e5e2012-09-12 15:17:447435 context.set_transport_security_state(&transport_security_state);
7436 context.Init();
7437
[email protected]9e6968d2014-05-07 21:46:267438 TransportSecurityState::DomainState dynamic_domain_state;
7439 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7440 "www.google.com", &dynamic_domain_state));
7441
[email protected]316c1e5e2012-09-12 15:17:447442 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197443 scoped_ptr<URLRequest> r(context.CreateRequest(
7444 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367445 test_server.host_port_pair().port())),
7446 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447447
[email protected]f7022f32014-08-21 16:32:197448 r->Start();
7449 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447450
[email protected]255620da2013-08-19 13:14:297451 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447452
7453 EXPECT_EQ(1, d.response_started_count());
7454 EXPECT_FALSE(d.received_data_before_response());
7455 EXPECT_TRUE(d.have_certificate_errors());
7456 EXPECT_TRUE(d.certificate_errors_are_fatal());
7457
[email protected]9e6968d2014-05-07 21:46:267458 // Get a fresh copy of the states, and check that they haven't changed.
7459 TransportSecurityState::DomainState new_static_domain_state;
7460 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127461 "www.google.com", &new_static_domain_state));
[email protected]9e6968d2014-05-07 21:46:267462 TransportSecurityState::DomainState new_dynamic_domain_state;
7463 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7464 "www.google.com", &new_dynamic_domain_state));
7465
7466 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
7467 static_domain_state.sts.upgrade_mode);
7468 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
7469 static_domain_state.sts.include_subdomains);
7470 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
7471 static_domain_state.pkp.include_subdomains);
7472 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
7473 static_domain_state.pkp.spki_hashes));
7474 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
7475 static_domain_state.pkp.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:447476}
7477
[email protected]8ccc69f2012-11-28 19:52:147478// Make sure HSTS preserves a POST request's method and body.
7479TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7480 static const char kData[] = "hello world";
7481
[email protected]ce7d0cbc2013-05-03 18:57:227482 SpawnedTestServer::SSLOptions ssl_options(
7483 SpawnedTestServer::SSLOptions::CERT_OK);
7484 SpawnedTestServer test_server(
7485 SpawnedTestServer::TYPE_HTTPS,
7486 ssl_options,
7487 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:147488 ASSERT_TRUE(test_server.Start());
7489
7490
7491 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7492 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:227493 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7494 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:147495 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:147496
7497 // Force https for www.somewhere.com.
7498 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:207499 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7500 bool include_subdomains = false;
7501 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7502 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:147503
7504 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7505
7506 TestURLRequestContext context(true);
7507 context.set_host_resolver(&host_resolver);
7508 context.set_transport_security_state(&transport_security_state);
7509 context.set_network_delegate(&network_delegate);
7510 context.Init();
7511
7512 TestDelegate d;
7513 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7514 // cause a certificate error. Ignore the error.
7515 d.set_allow_certificate_errors(true);
7516
[email protected]f7022f32014-08-21 16:32:197517 scoped_ptr<URLRequest> req(context.CreateRequest(
7518 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:367519 test_server.host_port_pair().port())),
7520 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197521 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077522 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:147523
[email protected]f7022f32014-08-21 16:32:197524 req->Start();
[email protected]255620da2013-08-19 13:14:297525 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:147526
[email protected]f7022f32014-08-21 16:32:197527 EXPECT_EQ("https", req->url().scheme());
7528 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:147529 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:407530
7531 LoadTimingInfo load_timing_info;
7532 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7533 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7534 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:147535}
7536
rob4e0be1f2014-09-11 23:40:227537// Make sure that the CORS headers are added to cross-origin HSTS redirects.
7538TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7539 static const char kOriginHeaderValue[] = "http://www.example.com";
7540
7541 SpawnedTestServer::SSLOptions ssl_options(
7542 SpawnedTestServer::SSLOptions::CERT_OK);
7543 SpawnedTestServer test_server(
7544 SpawnedTestServer::TYPE_HTTPS,
7545 ssl_options,
7546 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7547 ASSERT_TRUE(test_server.Start());
7548
7549 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7550 // address, so a MockHostResolver is needed to redirect example.net to the
7551 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7552 MockHostResolver host_resolver;
7553
7554 TransportSecurityState transport_security_state;
7555 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7556 bool include_subdomains = false;
7557 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7558
7559 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7560
7561 MockCertVerifier cert_verifier;
7562 cert_verifier.set_default_result(OK);
7563
7564 TestURLRequestContext context(true);
7565 context.set_host_resolver(&host_resolver);
7566 context.set_transport_security_state(&transport_security_state);
7567 context.set_network_delegate(&network_delegate);
7568 context.set_cert_verifier(&cert_verifier);
7569 context.Init();
7570
7571 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7572 test_server.host_port_pair().port()));
7573 url::Replacements<char> replacements;
7574 const char kNewScheme[] = "https";
7575 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7576 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7577
7578 TestDelegate d;
7579 // Quit on redirect to allow response header inspection upon redirect.
7580 d.set_quit_on_redirect(true);
7581
davidben151423e2015-03-23 18:48:367582 scoped_ptr<URLRequest> req(
7583 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:227584 // Set Origin header to simulate a cross-origin request.
7585 HttpRequestHeaders request_headers;
7586 request_headers.SetHeader("Origin", kOriginHeaderValue);
7587 req->SetExtraRequestHeaders(request_headers);
7588
7589 req->Start();
7590 base::RunLoop().Run();
7591
7592 EXPECT_EQ(1, d.received_redirect_count());
7593
7594 const HttpResponseHeaders* headers = req->response_headers();
7595 std::string redirect_location;
7596 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7597 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7598
7599 std::string received_cors_header;
7600 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7601 &received_cors_header));
7602 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7603}
7604
Adam Ricecb76ac62015-02-20 05:33:257605// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
7606// are performed in net/websockets/websocket_end_to_end_test.cc.
7607TEST(WebSocketURLRequestTest, HSTSApplied) {
7608 TestNetworkDelegate network_delegate;
7609 TransportSecurityState transport_security_state;
7610 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7611 bool include_subdomains = false;
7612 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7613 TestURLRequestContext context(true);
7614 context.set_transport_security_state(&transport_security_state);
7615 context.set_network_delegate(&network_delegate);
7616 context.Init();
7617 GURL ws_url("ws://example.net/echo");
7618 TestDelegate delegate;
7619 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367620 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:257621 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
7622 EXPECT_TRUE(ws_url.SchemeIs("wss"));
7623}
7624
[email protected]316c1e5e2012-09-12 15:17:447625namespace {
7626
7627class SSLClientAuthTestDelegate : public TestDelegate {
7628 public:
7629 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7630 }
dchengb03027d2014-10-21 12:00:207631 void OnCertificateRequested(URLRequest* request,
7632 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:447633 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:347634 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:447635 }
7636 int on_certificate_requested_count() {
7637 return on_certificate_requested_count_;
7638 }
7639 private:
7640 int on_certificate_requested_count_;
7641};
7642
7643} // namespace
7644
7645// TODO(davidben): Test the rest of the code. Specifically,
7646// - Filtering which certificates to select.
7647// - Sending a certificate back.
7648// - Getting a certificate request in an SSL renegotiation sending the
7649// HTTP request.
7650TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227651 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447652 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:227653 SpawnedTestServer test_server(
7654 SpawnedTestServer::TYPE_HTTPS,
7655 ssl_options,
7656 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447657 ASSERT_TRUE(test_server.Start());
7658
7659 SSLClientAuthTestDelegate d;
7660 {
[email protected]f7022f32014-08-21 16:32:197661 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367662 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447663
[email protected]f7022f32014-08-21 16:32:197664 r->Start();
7665 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447666
[email protected]255620da2013-08-19 13:14:297667 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447668
7669 EXPECT_EQ(1, d.on_certificate_requested_count());
7670 EXPECT_FALSE(d.received_data_before_response());
7671 EXPECT_EQ(0, d.bytes_received());
7672
7673 // Send no certificate.
7674 // TODO(davidben): Get temporary client cert import (with keys) working on
7675 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:197676 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:447677
[email protected]255620da2013-08-19 13:14:297678 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447679
7680 EXPECT_EQ(1, d.response_started_count());
7681 EXPECT_FALSE(d.received_data_before_response());
7682 EXPECT_NE(0, d.bytes_received());
7683 }
7684}
7685
7686TEST_F(HTTPSRequestTest, ResumeTest) {
7687 // Test that we attempt a session resume when making two connections to the
7688 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:227689 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447690 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227691 SpawnedTestServer test_server(
7692 SpawnedTestServer::TYPE_HTTPS,
7693 ssl_options,
7694 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447695 ASSERT_TRUE(test_server.Start());
7696
7697 SSLClientSocket::ClearSessionCache();
7698
7699 {
7700 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197701 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367702 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447703
[email protected]f7022f32014-08-21 16:32:197704 r->Start();
7705 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447706
[email protected]255620da2013-08-19 13:14:297707 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447708
7709 EXPECT_EQ(1, d.response_started_count());
7710 }
7711
7712 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7713 CloseAllConnections();
7714
7715 {
7716 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197717 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367718 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447719
[email protected]f7022f32014-08-21 16:32:197720 r->Start();
7721 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447722
[email protected]255620da2013-08-19 13:14:297723 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447724
7725 // The response will look like;
7726 // insert abc
7727 // lookup abc
7728 // insert xyz
7729 //
7730 // With a newline at the end which makes the split think that there are
7731 // four lines.
7732
7733 EXPECT_EQ(1, d.response_started_count());
7734 std::vector<std::string> lines;
7735 base::SplitString(d.data_received(), '\n', &lines);
7736 ASSERT_EQ(4u, lines.size()) << d.data_received();
7737
7738 std::string session_id;
7739
7740 for (size_t i = 0; i < 2; i++) {
7741 std::vector<std::string> parts;
7742 base::SplitString(lines[i], '\t', &parts);
7743 ASSERT_EQ(2u, parts.size());
7744 if (i == 0) {
7745 EXPECT_EQ("insert", parts[0]);
7746 session_id = parts[1];
7747 } else {
7748 EXPECT_EQ("lookup", parts[0]);
7749 EXPECT_EQ(session_id, parts[1]);
7750 }
7751 }
7752 }
7753}
7754
Adam Langley32352ad2014-10-14 22:31:007755// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7756// the result of fetching "ssl-session-cache" from the test server, indicates
7757// that exactly two different sessions were inserted, with no lookups etc.
7758static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7759 std::vector<std::string> lines;
7760 base::SplitString(session_info, '\n', &lines);
7761 ASSERT_EQ(3u, lines.size()) << session_info;
7762
7763 std::string session_id;
7764 for (size_t i = 0; i < 2; i++) {
7765 std::vector<std::string> parts;
7766 base::SplitString(lines[i], '\t', &parts);
7767 ASSERT_EQ(2u, parts.size());
7768 EXPECT_EQ("insert", parts[0]);
7769 if (i == 0) {
7770 session_id = parts[1];
7771 } else {
7772 EXPECT_NE(session_id, parts[1]);
7773 }
7774 }
7775}
7776
[email protected]316c1e5e2012-09-12 15:17:447777TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7778 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7779 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:227780 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447781 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227782 SpawnedTestServer test_server(
7783 SpawnedTestServer::TYPE_HTTPS,
7784 ssl_options,
7785 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447786 ASSERT_TRUE(test_server.Start());
7787
7788 SSLClientSocket::ClearSessionCache();
7789
7790 {
7791 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197792 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367793 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447794
[email protected]f7022f32014-08-21 16:32:197795 r->Start();
7796 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447797
[email protected]255620da2013-08-19 13:14:297798 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447799
7800 EXPECT_EQ(1, d.response_started_count());
7801 }
7802
7803 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7804 HttpNetworkSession::Params params;
7805 params.host_resolver = default_context_.host_resolver();
7806 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:117807 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:447808 params.proxy_service = default_context_.proxy_service();
7809 params.ssl_config_service = default_context_.ssl_config_service();
7810 params.http_auth_handler_factory =
7811 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:417812 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:447813 params.http_server_properties = default_context_.http_server_properties();
7814 params.ssl_session_cache_shard = "alternate";
7815
[email protected]cba24642014-08-15 20:49:597816 scoped_ptr<HttpCache> cache(new HttpCache(
7817 new HttpNetworkSession(params),
7818 HttpCache::DefaultBackend::InMemory(0)));
[email protected]316c1e5e2012-09-12 15:17:447819
7820 default_context_.set_http_transaction_factory(cache.get());
7821
7822 {
7823 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197824 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367825 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447826
[email protected]f7022f32014-08-21 16:32:197827 r->Start();
7828 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447829
[email protected]255620da2013-08-19 13:14:297830 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447831
7832 // The response will look like;
7833 // insert abc
7834 // insert xyz
7835 //
7836 // With a newline at the end which makes the split think that there are
7837 // three lines.
7838
7839 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:007840 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447841 }
7842}
7843
davidben8ecc3072014-09-03 23:19:097844#if defined(OS_WIN)
7845
7846namespace {
7847
7848bool IsECDSACipherSuite(uint16_t cipher_suite) {
7849 const char* key_exchange;
7850 const char* cipher;
7851 const char* mac;
7852 bool is_aead;
7853 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7854 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7855}
7856
7857} // namespace
7858
7859// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7860// verified.
davidben9399c952014-10-07 04:09:117861TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:097862 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7863 LOG(INFO) << "Skipping test on this version.";
7864 return;
7865 }
7866
7867 SpawnedTestServer test_server(
7868 SpawnedTestServer::TYPE_HTTPS,
7869 SpawnedTestServer::kLocalhost,
7870 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7871 ASSERT_TRUE(test_server.Start());
7872
7873 TestDelegate d;
7874 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367875 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:097876 r->Start();
7877 EXPECT_TRUE(r->is_pending());
7878
7879 base::RunLoop().Run();
7880
7881 EXPECT_EQ(1, d.response_started_count());
7882 std::vector<std::string> lines;
7883 base::SplitString(d.data_received(), '\n', &lines);
7884
7885 for (size_t i = 0; i < lines.size(); i++) {
7886 int cipher_suite;
7887 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7888 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7889 << "ClientHello advertised " << cipher_suite;
7890 }
7891}
7892
7893#endif // OS_WIN
7894
Adam Langley32352ad2014-10-14 22:31:007895class TestSSLConfigService : public SSLConfigService {
7896 public:
7897 TestSSLConfigService(bool ev_enabled,
7898 bool online_rev_checking,
7899 bool rev_checking_required_local_anchors)
7900 : ev_enabled_(ev_enabled),
7901 online_rev_checking_(online_rev_checking),
7902 rev_checking_required_local_anchors_(
7903 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:027904 min_version_(kDefaultSSLVersionMin),
7905 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7906
7907 void set_min_version(uint16 version) {
7908 min_version_ = version;
7909 }
Adam Langley32352ad2014-10-14 22:31:007910
7911 void set_fallback_min_version(uint16 version) {
7912 fallback_min_version_ = version;
7913 }
7914
7915 // SSLConfigService:
dchengb03027d2014-10-21 12:00:207916 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:007917 *config = SSLConfig();
7918 config->rev_checking_enabled = online_rev_checking_;
7919 config->verify_ev_cert = ev_enabled_;
7920 config->rev_checking_required_local_anchors =
7921 rev_checking_required_local_anchors_;
7922 if (fallback_min_version_) {
7923 config->version_fallback_min = fallback_min_version_;
7924 }
Adam Langleyac6f24b42014-10-31 20:24:027925 if (min_version_) {
7926 config->version_min = min_version_;
7927 }
Adam Langley32352ad2014-10-14 22:31:007928 }
7929
7930 protected:
dchengb03027d2014-10-21 12:00:207931 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:007932
7933 private:
7934 const bool ev_enabled_;
7935 const bool online_rev_checking_;
7936 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:027937 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:007938 uint16 fallback_min_version_;
7939};
7940
7941class FallbackTestURLRequestContext : public TestURLRequestContext {
7942 public:
7943 explicit FallbackTestURLRequestContext(bool delay_initialization)
7944 : TestURLRequestContext(delay_initialization) {}
7945
7946 void set_fallback_min_version(uint16 version) {
7947 TestSSLConfigService *ssl_config_service =
7948 new TestSSLConfigService(true /* check for EV */,
7949 false /* online revocation checking */,
7950 false /* require rev. checking for local
7951 anchors */);
Adam Langley32352ad2014-10-14 22:31:007952 ssl_config_service->set_fallback_min_version(version);
7953 set_ssl_config_service(ssl_config_service);
7954 }
7955};
7956
[email protected]48d2b7c52014-06-27 01:16:557957class HTTPSFallbackTest : public testing::Test {
7958 public:
Adam Langley32352ad2014-10-14 22:31:007959 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:297960 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:557961
7962 protected:
7963 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
7964 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:007965 context_.Init();
7966 delegate_.set_allow_certificate_errors(true);
7967
[email protected]48d2b7c52014-06-27 01:16:557968 SpawnedTestServer test_server(
7969 SpawnedTestServer::TYPE_HTTPS,
7970 ssl_options,
7971 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7972 ASSERT_TRUE(test_server.Start());
7973
davidben151423e2015-03-23 18:48:367974 request_ = context_.CreateRequest(test_server.GetURL(std::string()),
7975 DEFAULT_PRIORITY, &delegate_);
[email protected]48d2b7c52014-06-27 01:16:557976 request_->Start();
7977
7978 base::RunLoop().Run();
7979 }
7980
Adam Langley32352ad2014-10-14 22:31:007981 void set_fallback_min_version(uint16 version) {
7982 context_.set_fallback_min_version(version);
7983 }
7984
[email protected]48d2b7c52014-06-27 01:16:557985 void ExpectConnection(int version) {
7986 EXPECT_EQ(1, delegate_.response_started_count());
7987 EXPECT_NE(0, delegate_.bytes_received());
7988 EXPECT_EQ(version, SSLConnectionStatusToVersion(
7989 request_->ssl_info().connection_status));
7990 EXPECT_TRUE(request_->ssl_info().connection_status &
7991 SSL_CONNECTION_VERSION_FALLBACK);
7992 }
7993
7994 void ExpectFailure(int error) {
7995 EXPECT_EQ(1, delegate_.response_started_count());
7996 EXPECT_FALSE(request_->status().is_success());
7997 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
7998 EXPECT_EQ(error, request_->status().error());
7999 }
8000
8001 private:
8002 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008003 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558004 scoped_ptr<URLRequest> request_;
8005};
8006
8007// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
8008// than necessary.
8009TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
8010 SpawnedTestServer::SSLOptions ssl_options(
8011 SpawnedTestServer::SSLOptions::CERT_OK);
8012 ssl_options.tls_intolerant =
8013 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8014
8015 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8016 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
8017}
8018
8019// This test is disabled on Android because the remote test server doesn't cause
8020// a TCP reset.
8021#if !defined(OS_ANDROID)
8022// Tests fallback to TLS 1.0 on connection reset.
8023TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
8024 SpawnedTestServer::SSLOptions ssl_options(
8025 SpawnedTestServer::SSLOptions::CERT_OK);
8026 ssl_options.tls_intolerant =
8027 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8028 ssl_options.tls_intolerance_type =
8029 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8030
8031 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8032 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
8033}
8034#endif // !OS_ANDROID
8035
[email protected]12833302014-07-02 01:57:318036// Tests that we don't fallback on handshake failure with servers that implement
8037// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558038TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558039 SpawnedTestServer::SSLOptions ssl_options(
8040 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438041 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558042 // a version fallback.
8043 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438044 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558045 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8046 // connections are rejected.
8047 ssl_options.fallback_scsv_enabled = true;
8048
8049 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8050
8051 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8052 // intolerance. If the fallback SCSV is processed when the original error
8053 // that caused the fallback should be returned, which should be
8054 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8055 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8056}
8057
[email protected]12833302014-07-02 01:57:318058// Tests that we don't fallback on connection closed with servers that implement
8059// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318060TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318061 SpawnedTestServer::SSLOptions ssl_options(
8062 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438063 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318064 // a version fallback.
8065 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438066 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318067 ssl_options.tls_intolerance_type =
8068 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8069 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8070 // connections are rejected.
8071 ssl_options.fallback_scsv_enabled = true;
8072
8073 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8074
8075 // The original error should be replayed on rejected fallback.
8076 ExpectFailure(ERR_CONNECTION_CLOSED);
8077}
8078
davidbenb937d6c2015-05-14 04:53:428079// Tests that the SSLv3 fallback doesn't happen.
[email protected]48d2b7c52014-06-27 01:16:558080TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
8081 SpawnedTestServer::SSLOptions ssl_options(
8082 SpawnedTestServer::SSLOptions::CERT_OK);
8083 ssl_options.tls_intolerant =
8084 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8085
8086 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
Adam Langleyac6f24b42014-10-31 20:24:028087 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
Adam Langley32352ad2014-10-14 22:31:008088}
8089
davidbenb937d6c2015-05-14 04:53:428090// Tests that the TLSv1 fallback triggers on closed connections.
[email protected]48d2b7c52014-06-27 01:16:558091TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
8092 SpawnedTestServer::SSLOptions ssl_options(
8093 SpawnedTestServer::SSLOptions::CERT_OK);
8094 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428095 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558096 ssl_options.tls_intolerance_type =
8097 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
[email protected]48d2b7c52014-06-27 01:16:558098
8099 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb937d6c2015-05-14 04:53:428100 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
[email protected]48d2b7c52014-06-27 01:16:558101}
8102
davidbenb937d6c2015-05-14 04:53:428103// Test that fallback probe connections don't cause sessions to be cached.
8104TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008105 SpawnedTestServer::SSLOptions ssl_options(
8106 SpawnedTestServer::SSLOptions::CERT_OK);
8107 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428108 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008109 ssl_options.tls_intolerance_type =
8110 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8111 ssl_options.record_resume = true;
8112
8113 SpawnedTestServer test_server(
8114 SpawnedTestServer::TYPE_HTTPS,
8115 ssl_options,
8116 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8117 ASSERT_TRUE(test_server.Start());
8118
8119 SSLClientSocket::ClearSessionCache();
8120
davidbenb937d6c2015-05-14 04:53:428121 // Make a connection that does a probe fallback to TLSv1 but fails because
8122 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008123 // be inserted locally.
8124 {
8125 TestDelegate delegate;
8126 FallbackTestURLRequestContext context(true);
8127
davidbenb937d6c2015-05-14 04:53:428128 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008129 context.Init();
8130 scoped_ptr<URLRequest> request(context.CreateRequest(
davidben151423e2015-03-23 18:48:368131 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008132 request->Start();
8133
8134 base::RunLoop().Run();
8135
8136 EXPECT_EQ(1, delegate.response_started_count());
8137 EXPECT_FALSE(request->status().is_success());
8138 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8139 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8140 request->status().error());
8141 }
8142
davidbenb937d6c2015-05-14 04:53:428143 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008144 {
8145 TestDelegate delegate;
8146 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428147 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008148
8149 context.Init();
davidben151423e2015-03-23 18:48:368150 scoped_ptr<URLRequest> request(context.CreateRequest(
8151 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008152 request->Start();
8153
8154 base::RunLoop().Run();
8155
8156 EXPECT_EQ(1, delegate.response_started_count());
8157 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428158 EXPECT_EQ(
8159 SSL_CONNECTION_VERSION_TLS1,
8160 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008161 EXPECT_TRUE(request->ssl_info().connection_status &
8162 SSL_CONNECTION_VERSION_FALLBACK);
8163
8164 std::vector<std::string> lines;
8165 // If no sessions were cached then the server should have seen two sessions
8166 // inserted with no lookups.
8167 AssertTwoDistinctSessionsInserted(delegate.data_received());
8168 }
8169}
8170
[email protected]a8fed1742013-12-27 02:14:248171class HTTPSSessionTest : public testing::Test {
8172 public:
8173 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598174 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248175
8176 default_context_.set_network_delegate(&default_network_delegate_);
8177 default_context_.set_cert_verifier(&cert_verifier_);
8178 default_context_.Init();
8179 }
dcheng67be2b1f2014-10-27 21:47:298180 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248181
8182 protected:
8183 MockCertVerifier cert_verifier_;
8184 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8185 TestURLRequestContext default_context_;
8186};
8187
8188// Tests that session resumption is not attempted if an invalid certificate
8189// is presented.
8190TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8191 SpawnedTestServer::SSLOptions ssl_options;
8192 ssl_options.record_resume = true;
8193 SpawnedTestServer test_server(
8194 SpawnedTestServer::TYPE_HTTPS,
8195 ssl_options,
8196 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8197 ASSERT_TRUE(test_server.Start());
8198
8199 SSLClientSocket::ClearSessionCache();
8200
8201 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598202 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248203 {
8204 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198205 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368206 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248207
[email protected]f7022f32014-08-21 16:32:198208 r->Start();
8209 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248210
8211 base::RunLoop().Run();
8212
8213 EXPECT_EQ(1, d.response_started_count());
8214 }
8215
8216 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8217 CloseAllConnections();
8218
8219 // Now change the certificate to be acceptable (so that the response is
8220 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598221 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248222 {
8223 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198224 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368225 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248226
[email protected]f7022f32014-08-21 16:32:198227 r->Start();
8228 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248229
8230 base::RunLoop().Run();
8231
8232 // The response will look like;
8233 // insert abc
8234 // insert xyz
8235 //
8236 // With a newline at the end which makes the split think that there are
8237 // three lines.
8238 //
8239 // If a session was presented (eg: a bug), then the response would look
8240 // like;
8241 // insert abc
8242 // lookup abc
8243 // insert xyz
8244
8245 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008246 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248247 }
8248}
8249
[email protected]dffe8242012-03-20 15:14:278250// This the fingerprint of the "Testing CA" certificate used by the testserver.
8251// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268252static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278253 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8254 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8255
[email protected]51523f52013-07-31 21:57:288256// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8257// testserver.
8258static const SHA256HashValue kOCSPTestCertSPKI = { {
8259 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8260 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8261 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8262 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8263} };
8264
[email protected]dffe8242012-03-20 15:14:278265// This is the policy OID contained in the certificates that testserver
8266// generates.
8267static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8268
8269class HTTPSOCSPTest : public HTTPSRequestTest {
8270 public:
8271 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098272 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088273 ev_test_policy_(
8274 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8275 kOCSPTestCertFingerprint,
8276 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028277 }
8278
dcheng67be2b1f2014-10-27 21:47:298279 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098280 SetupContext(&context_);
8281 context_.Init();
[email protected]dffe8242012-03-20 15:14:278282
[email protected]cba24642014-08-15 20:49:598283 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208284 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428285 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508286 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278287
davidben71f35ff2015-04-17 20:54:488288#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098289 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278290 EnsureNSSHttpIOInit();
8291#endif
8292 }
8293
[email protected]ce7d0cbc2013-05-03 18:57:228294 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278295 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538296 // We always overwrite out_cert_status.
8297 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228298 SpawnedTestServer test_server(
8299 SpawnedTestServer::TYPE_HTTPS,
8300 ssl_options,
8301 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278302 ASSERT_TRUE(test_server.Start());
8303
8304 TestDelegate d;
8305 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:198306 scoped_ptr<URLRequest> r(context_.CreateRequest(
davidben151423e2015-03-23 18:48:368307 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198308 r->Start();
[email protected]dffe8242012-03-20 15:14:278309
[email protected]255620da2013-08-19 13:14:298310 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278311
8312 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198313 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278314 }
8315
dcheng67be2b1f2014-10-27 21:47:298316 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488317#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278318 ShutdownNSSHttpIO();
8319#endif
8320 }
8321
[email protected]a13234c2012-03-20 21:45:028322 protected:
8323 // SetupContext configures the URLRequestContext that will be used for making
8324 // connetions to testserver. This can be overridden in test subclasses for
8325 // different behaviour.
8326 virtual void SetupContext(URLRequestContext* context) {
8327 context->set_ssl_config_service(
8328 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208329 true /* online revocation checking */,
8330 false /* require rev. checking for local
8331 anchors */));
[email protected]a13234c2012-03-20 21:45:028332 }
8333
[email protected]dffe8242012-03-20 15:14:278334 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098335 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088336 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278337};
8338
[email protected]a13234c2012-03-20 21:45:028339static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018340#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028341 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8342 // have that ability on other platforms.
8343 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8344#else
8345 return 0;
8346#endif
8347}
8348
[email protected]3a86a712013-07-30 07:16:208349// SystemSupportsHardFailRevocationChecking returns true iff the current
8350// operating system supports revocation checking and can distinguish between
8351// situations where a given certificate lacks any revocation information (eg:
8352// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8353// revocation information cannot be obtained (eg: the CRL was unreachable).
8354// If it does not, then tests which rely on 'hard fail' behaviour should be
8355// skipped.
8356static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:488357#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:208358 return true;
8359#else
8360 return false;
8361#endif
8362}
8363
[email protected]a13234c2012-03-20 21:45:028364// SystemUsesChromiumEVMetadata returns true iff the current operating system
8365// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8366// several tests are effected because our testing EV certificate won't be
8367// recognised as EV.
8368static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328369#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578370 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8371 return false;
[email protected]e1b2d732014-03-28 16:20:328372#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8373 // On OS X and Android, we use the system to tell us whether a certificate is
8374 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018375 return false;
8376#else
8377 return true;
8378#endif
8379}
8380
[email protected]b6f2de32012-08-17 04:35:088381static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008382#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578383 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8384 return false;
8385#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028386 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8387#elif defined(OS_ANDROID)
8388 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8389 return false;
8390#else
8391 return true;
8392#endif
8393}
8394
davidbend1fb2f12014-11-08 02:51:008395static bool SystemSupportsOCSPStapling() {
davidben71f35ff2015-04-17 20:54:488396#if defined(USE_NSS_CERTS)
davidbend1fb2f12014-11-08 02:51:008397 return true;
8398#elif defined(OS_WIN)
8399 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8400#else
8401 return false;
8402#endif
8403}
8404
[email protected]dffe8242012-03-20 15:14:278405TEST_F(HTTPSOCSPTest, Valid) {
8406 if (!SystemSupportsOCSP()) {
8407 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8408 return;
8409 }
8410
[email protected]ce7d0cbc2013-05-03 18:57:228411 SpawnedTestServer::SSLOptions ssl_options(
8412 SpawnedTestServer::SSLOptions::CERT_AUTO);
8413 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278414
[email protected]924e9f92012-12-16 22:00:538415 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128416 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278417
8418 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8419
[email protected]a13234c2012-03-20 21:45:028420 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8421 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278422
8423 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8424}
8425
8426TEST_F(HTTPSOCSPTest, Revoked) {
8427 if (!SystemSupportsOCSP()) {
8428 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8429 return;
8430 }
8431
[email protected]ce7d0cbc2013-05-03 18:57:228432 SpawnedTestServer::SSLOptions ssl_options(
8433 SpawnedTestServer::SSLOptions::CERT_AUTO);
8434 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278435
8436 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128437 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278438
[email protected]a592c0432012-12-01 18:10:298439#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278440 // Doesn't pass on OS X yet for reasons that need to be investigated.
8441 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8442#endif
8443 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8444 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8445}
8446
8447TEST_F(HTTPSOCSPTest, Invalid) {
8448 if (!SystemSupportsOCSP()) {
8449 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8450 return;
8451 }
8452
[email protected]ce7d0cbc2013-05-03 18:57:228453 SpawnedTestServer::SSLOptions ssl_options(
8454 SpawnedTestServer::SSLOptions::CERT_AUTO);
8455 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:278456
[email protected]924e9f92012-12-16 22:00:538457 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128458 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278459
[email protected]a13234c2012-03-20 21:45:028460 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278461 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:278462
8463 // Without a positive OCSP response, we shouldn't show the EV status.
8464 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8465 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8466}
[email protected]a13234c2012-03-20 21:45:028467
davidbend1fb2f12014-11-08 02:51:008468TEST_F(HTTPSOCSPTest, ValidStapled) {
8469 if (!SystemSupportsOCSPStapling()) {
8470 LOG(WARNING)
8471 << "Skipping test because system doesn't support OCSP stapling";
8472 return;
8473 }
8474
8475 SpawnedTestServer::SSLOptions ssl_options(
8476 SpawnedTestServer::SSLOptions::CERT_AUTO);
8477 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8478 ssl_options.staple_ocsp_response = true;
8479 ssl_options.ocsp_server_unavailable = true;
8480
8481 CertStatus cert_status;
8482 DoConnection(ssl_options, &cert_status);
8483
8484 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8485
8486 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8487 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8488
8489 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8490}
8491
davidben6c3191b2014-11-21 22:38:048492// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:488493#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:048494#define MAYBE_RevokedStapled DISABLED_RevokedStapled
8495#else
8496#define MAYBE_RevokedStapled RevokedStapled
8497#endif
8498TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
davidbend1fb2f12014-11-08 02:51:008499 if (!SystemSupportsOCSPStapling()) {
8500 LOG(WARNING)
8501 << "Skipping test because system doesn't support OCSP stapling";
8502 return;
8503 }
8504
8505 SpawnedTestServer::SSLOptions ssl_options(
8506 SpawnedTestServer::SSLOptions::CERT_AUTO);
8507 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8508 ssl_options.staple_ocsp_response = true;
8509 ssl_options.ocsp_server_unavailable = true;
8510
8511 CertStatus cert_status;
8512 DoConnection(ssl_options, &cert_status);
8513
8514 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8515 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8516 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8517}
8518
[email protected]3a86a712013-07-30 07:16:208519class HTTPSHardFailTest : public HTTPSOCSPTest {
8520 protected:
dchengb03027d2014-10-21 12:00:208521 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:208522 context->set_ssl_config_service(
8523 new TestSSLConfigService(false /* check for EV */,
8524 false /* online revocation checking */,
8525 true /* require rev. checking for local
8526 anchors */));
8527 }
8528};
8529
[email protected]3a86a712013-07-30 07:16:208530TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8531 if (!SystemSupportsOCSP()) {
8532 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8533 return;
8534 }
8535
8536 if (!SystemSupportsHardFailRevocationChecking()) {
8537 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8538 << "revocation checking";
8539 return;
8540 }
8541
8542 SpawnedTestServer::SSLOptions ssl_options(
8543 SpawnedTestServer::SSLOptions::CERT_AUTO);
8544 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8545
8546 CertStatus cert_status;
8547 DoConnection(ssl_options, &cert_status);
8548
8549 EXPECT_EQ(CERT_STATUS_REVOKED,
8550 cert_status & CERT_STATUS_REVOKED);
8551
8552 // Without a positive OCSP response, we shouldn't show the EV status.
8553 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8554}
8555
[email protected]a13234c2012-03-20 21:45:028556class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8557 protected:
dchengb03027d2014-10-21 12:00:208558 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028559 context->set_ssl_config_service(
8560 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208561 false /* online revocation checking */,
8562 false /* require rev. checking for local
8563 anchors */));
[email protected]a13234c2012-03-20 21:45:028564 }
8565};
8566
8567TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8568 if (!SystemSupportsOCSP()) {
8569 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8570 return;
8571 }
8572
[email protected]ce7d0cbc2013-05-03 18:57:228573 SpawnedTestServer::SSLOptions ssl_options(
8574 SpawnedTestServer::SSLOptions::CERT_AUTO);
8575 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028576 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8577
[email protected]924e9f92012-12-16 22:00:538578 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128579 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028580
8581 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8582 cert_status & CERT_STATUS_ALL_ERRORS);
8583
8584 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088585 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8586 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028587}
8588
[email protected]be0fff62013-08-29 23:37:488589TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8590 if (!SystemSupportsOCSP()) {
8591 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8592 return;
8593 }
8594
8595 SpawnedTestServer::SSLOptions ssl_options(
8596 SpawnedTestServer::SSLOptions::CERT_AUTO);
8597 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8598 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8599
8600 CertStatus cert_status;
8601 DoConnection(ssl_options, &cert_status);
8602
8603 // Currently only works for Windows. When using NSS or OS X, it's not
8604 // possible to determine whether the check failed because of actual
8605 // revocation or because there was an OCSP failure.
8606#if defined(OS_WIN)
8607 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8608#else
8609 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8610#endif
8611
8612 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8613 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8614 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8615}
8616
[email protected]a13234c2012-03-20 21:45:028617TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8618 if (!SystemSupportsOCSP()) {
8619 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8620 return;
8621 }
8622
[email protected]ce7d0cbc2013-05-03 18:57:228623 SpawnedTestServer::SSLOptions ssl_options(
8624 SpawnedTestServer::SSLOptions::CERT_AUTO);
8625 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:028626 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8627
8628 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128629 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028630
8631 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8632
8633 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8634 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:088635 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8636 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028637}
8638
8639TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8640 if (!SystemSupportsOCSP()) {
8641 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8642 return;
8643 }
8644
[email protected]ce7d0cbc2013-05-03 18:57:228645 SpawnedTestServer::SSLOptions ssl_options(
8646 SpawnedTestServer::SSLOptions::CERT_AUTO);
8647 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028648 SSLConfigService::SetCRLSet(
8649 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8650
8651 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128652 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028653
8654 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8655 cert_status & CERT_STATUS_ALL_ERRORS);
8656
8657 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088658 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8659 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028660}
8661
[email protected]51523f52013-07-31 21:57:288662TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8663 if (!SystemSupportsOCSP()) {
8664 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8665 return;
8666 }
8667
8668 SpawnedTestServer::SSLOptions ssl_options(
8669 SpawnedTestServer::SSLOptions::CERT_AUTO);
8670 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8671 SSLConfigService::SetCRLSet(
8672 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8673 false, &kOCSPTestCertSPKI, "")));
8674
8675 CertStatus cert_status;
8676 DoConnection(ssl_options, &cert_status);
8677
8678 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8679 // revocation check for EV.
8680 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8681 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8682 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8683 EXPECT_FALSE(
8684 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8685}
8686
8687TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8688 if (!SystemSupportsOCSP()) {
8689 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8690 return;
8691 }
8692
[email protected]ce7d0cbc2013-05-03 18:57:228693 SpawnedTestServer::SSLOptions ssl_options(
8694 SpawnedTestServer::SSLOptions::CERT_AUTO);
8695 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028696 SSLConfigService::SetCRLSet(
8697 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8698
[email protected]51523f52013-07-31 21:57:288699 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:128700 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028701
[email protected]51523f52013-07-31 21:57:288702 // Even with a fresh CRLSet, we should still do online revocation checks when
8703 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8704 // test.
8705 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8706 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:028707
[email protected]51523f52013-07-31 21:57:288708 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:028709 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:288710 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028711}
8712
[email protected]b6f2de32012-08-17 04:35:088713TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8714 // Test that when EV verification is requested, but online revocation
8715 // checking is disabled, and the leaf certificate is not in fact EV, that
8716 // no revocation checking actually happens.
8717 if (!SystemSupportsOCSP()) {
8718 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8719 return;
8720 }
8721
8722 // Unmark the certificate's OID as EV, which should disable revocation
8723 // checking (as per the user preference)
8724 ev_test_policy_.reset();
8725
[email protected]ce7d0cbc2013-05-03 18:57:228726 SpawnedTestServer::SSLOptions ssl_options(
8727 SpawnedTestServer::SSLOptions::CERT_AUTO);
8728 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:088729 SSLConfigService::SetCRLSet(
8730 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8731
8732 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128733 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:088734
8735 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8736
8737 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8738 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8739}
8740
[email protected]a13234c2012-03-20 21:45:028741class HTTPSCRLSetTest : public HTTPSOCSPTest {
8742 protected:
dchengb03027d2014-10-21 12:00:208743 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028744 context->set_ssl_config_service(
8745 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208746 false /* online revocation checking */,
8747 false /* require rev. checking for local
8748 anchors */));
[email protected]a13234c2012-03-20 21:45:028749 }
8750};
8751
8752TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:228753 SpawnedTestServer::SSLOptions ssl_options(
8754 SpawnedTestServer::SSLOptions::CERT_AUTO);
8755 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028756 SSLConfigService::SetCRLSet(
8757 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8758
[email protected]924e9f92012-12-16 22:00:538759 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128760 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028761
8762 // If we're not trying EV verification then, even if the CRLSet has expired,
8763 // we don't fall back to online revocation checks.
8764 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8765 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8766 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8767}
[email protected]51523f52013-07-31 21:57:288768
8769TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:308770#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:288771 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8772 return;
8773#endif
8774
8775 SpawnedTestServer::SSLOptions ssl_options(
8776 SpawnedTestServer::SSLOptions::CERT_AUTO);
8777 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8778 ssl_options.cert_serial = 10;
8779 SSLConfigService::SetCRLSet(
8780 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8781 false, &kOCSPTestCertSPKI, "\x0a")));
8782
8783 CertStatus cert_status = 0;
8784 DoConnection(ssl_options, &cert_status);
8785
8786 // If the certificate is recorded as revoked in the CRLSet, that should be
8787 // reflected without online revocation checking.
8788 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8789 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8790 EXPECT_FALSE(
8791 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8792}
[email protected]316c1e5e2012-09-12 15:17:448793#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278794
[email protected]316c1e5e2012-09-12 15:17:448795#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:318796class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:118797 public:
[email protected]d9fca99a2012-02-24 16:16:208798 URLRequestTestFTP()
[email protected]ce7d0cbc2013-05-03 18:57:228799 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:158800 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:118801 }
8802
[email protected]b89ca032009-08-31 21:41:318803 protected:
[email protected]ce7d0cbc2013-05-03 18:57:228804 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:318805};
8806
[email protected]d2a133182012-08-05 16:44:088807// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:098808TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:088809 ASSERT_TRUE(test_server_.Start());
8810
[email protected]9d5730b2012-08-24 17:42:498811 URLRequestJobFactoryImpl job_factory;
[email protected]e0f35c92013-05-08 16:04:348812 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
[email protected]d2a133182012-08-05 16:44:088813
8814 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:088815 job_factory.SetProtocolHandler(
8816 "ftp",
[email protected]e0f35c92013-05-08 16:04:348817 new FtpProtocolHandler(&ftp_transaction_factory));
[email protected]d2a133182012-08-05 16:44:088818 default_context_.set_job_factory(&job_factory);
8819
8820 TestDelegate d;
8821 {
davidben151423e2015-03-23 18:48:368822 scoped_ptr<URLRequest> r(
8823 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198824 r->Start();
8825 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:088826
[email protected]255620da2013-08-19 13:14:298827 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:088828
[email protected]f7022f32014-08-21 16:32:198829 EXPECT_FALSE(r->is_pending());
8830 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8831 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:088832 }
8833}
8834
[email protected]5accf7332009-11-24 03:41:388835// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128836TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:118837 ASSERT_TRUE(test_server_.Start());
8838
[email protected]a25e90e2009-09-09 17:05:378839 TestDelegate d;
8840 {
[email protected]f7022f32014-08-21 16:32:198841 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368842 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198843 r->Start();
8844 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378845
[email protected]255620da2013-08-19 13:14:298846 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:378847
[email protected]f7022f32014-08-21 16:32:198848 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378849 EXPECT_EQ(1, d.response_started_count());
8850 EXPECT_FALSE(d.received_data_before_response());
8851 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:198852 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198853 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198854 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198855 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:378856 }
8857}
8858
[email protected]7df70012010-02-04 00:09:558859// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128860TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:118861 ASSERT_TRUE(test_server_.Start());
8862
[email protected]6cdfd7f2013-02-08 20:40:158863 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278864 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028865 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278866 TestDelegate d;
8867 {
[email protected]f7022f32014-08-21 16:32:198868 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368869 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198870 r->Start();
8871 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278872
[email protected]255620da2013-08-19 13:14:298873 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278874
8875 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498876 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278877
[email protected]f7022f32014-08-21 16:32:198878 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278879 EXPECT_EQ(1, d.response_started_count());
8880 EXPECT_FALSE(d.received_data_before_response());
8881 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:198882 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198883 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198884 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198885 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278886 }
8887}
8888
[email protected]e9ecbd12009-12-20 18:44:408889// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128890TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:118891 ASSERT_TRUE(test_server_.Start());
8892
[email protected]6cdfd7f2013-02-08 20:40:158893 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278894 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028895 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278896 TestDelegate d;
8897 {
[email protected]f7022f32014-08-21 16:32:198898 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]95409e12010-08-17 20:07:118899 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
davidben151423e2015-03-23 18:48:368900 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198901 r->Start();
8902 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278903
[email protected]255620da2013-08-19 13:14:298904 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278905
8906 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498907 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278908
[email protected]f7022f32014-08-21 16:32:198909 EXPECT_FALSE(r->is_pending());
[email protected]6d81b482011-02-22 19:47:198910 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198911 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198912 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198913 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278914 EXPECT_EQ(1, d.response_started_count());
8915 EXPECT_FALSE(d.received_data_before_response());
8916 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:258917
8918 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198919 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258920 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:278921 }
8922}
8923
[email protected]49abd652010-08-05 05:04:538924// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128925TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:118926 ASSERT_TRUE(test_server_.Start());
8927
[email protected]6cdfd7f2013-02-08 20:40:158928 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278929 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028930 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278931 TestDelegate d;
8932 {
[email protected]f7022f32014-08-21 16:32:198933 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8934 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8935 "wrong_password"),
davidben151423e2015-03-23 18:48:368936 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198937 r->Start();
8938 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278939
[email protected]255620da2013-08-19 13:14:298940 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278941
8942 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498943 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278944
[email protected]f7022f32014-08-21 16:32:198945 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278946 EXPECT_EQ(1, d.response_started_count());
8947 EXPECT_FALSE(d.received_data_before_response());
8948 EXPECT_EQ(d.bytes_received(), 0);
8949 }
8950}
8951
[email protected]cde4e80d2009-10-16 19:58:158952// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128953TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:118954 ASSERT_TRUE(test_server_.Start());
8955
[email protected]6cdfd7f2013-02-08 20:40:158956 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:588957 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8958 app_path = app_path.AppendASCII("LICENSE");
8959 TestDelegate d;
8960 // Set correct login credentials. The delegate will be asked for them when
8961 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588962 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:588963 {
[email protected]f7022f32014-08-21 16:32:198964 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8965 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8966 "wrong_password"),
davidben151423e2015-03-23 18:48:368967 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198968 r->Start();
8969 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588970
[email protected]255620da2013-08-19 13:14:298971 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:588972
8973 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498974 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:588975
[email protected]f7022f32014-08-21 16:32:198976 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588977 EXPECT_EQ(1, d.response_started_count());
8978 EXPECT_FALSE(d.received_data_before_response());
8979 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8980 }
8981}
8982
[email protected]49abd652010-08-05 05:04:538983// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128984TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:118985 ASSERT_TRUE(test_server_.Start());
8986
[email protected]6cdfd7f2013-02-08 20:40:158987 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278988 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028989 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278990 TestDelegate d;
8991 {
davidben151423e2015-03-23 18:48:368992 scoped_ptr<URLRequest> r(
8993 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
8994 "/LICENSE", "wrong_user", "chrome"),
8995 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198996 r->Start();
8997 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278998
[email protected]255620da2013-08-19 13:14:298999 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279000
9001 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499002 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:279003
[email protected]f7022f32014-08-21 16:32:199004 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279005 EXPECT_EQ(1, d.response_started_count());
9006 EXPECT_FALSE(d.received_data_before_response());
9007 EXPECT_EQ(d.bytes_received(), 0);
9008 }
9009}
[email protected]8b8a197d2009-08-26 15:57:589010
[email protected]cde4e80d2009-10-16 19:58:159011// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:129012TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:119013 ASSERT_TRUE(test_server_.Start());
9014
[email protected]6cdfd7f2013-02-08 20:40:159015 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:589016 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
9017 app_path = app_path.AppendASCII("LICENSE");
9018 TestDelegate d;
9019 // Set correct login credentials. The delegate will be asked for them when
9020 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589021 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589022 {
davidben151423e2015-03-23 18:48:369023 scoped_ptr<URLRequest> r(
9024 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9025 "/LICENSE", "wrong_user", "chrome"),
9026 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199027 r->Start();
9028 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589029
[email protected]255620da2013-08-19 13:14:299030 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589031
9032 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499033 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:589034
[email protected]f7022f32014-08-21 16:32:199035 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589036 EXPECT_EQ(1, d.response_started_count());
9037 EXPECT_FALSE(d.received_data_before_response());
9038 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
9039 }
9040}
[email protected]60a3df52009-09-22 16:13:249041
[email protected]cde4e80d2009-10-16 19:58:159042// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:129043TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:119044 ASSERT_TRUE(test_server_.Start());
9045
[email protected]6cdfd7f2013-02-08 20:40:159046 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:249047 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
9048 app_path = app_path.AppendASCII("LICENSE");
9049
9050 scoped_ptr<TestDelegate> d(new TestDelegate);
9051 {
9052 // Pass correct login identity in the URL.
[email protected]f7022f32014-08-21 16:32:199053 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:199054 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
davidben151423e2015-03-23 18:48:369055 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199056 r->Start();
9057 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249058
[email protected]255620da2013-08-19 13:14:299059 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249060
9061 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499062 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249063
[email protected]f7022f32014-08-21 16:32:199064 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249065 EXPECT_EQ(1, d->response_started_count());
9066 EXPECT_FALSE(d->received_data_before_response());
9067 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9068 }
9069
9070 d.reset(new TestDelegate);
9071 {
9072 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199073 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369074 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199075 r->Start();
9076 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249077
[email protected]255620da2013-08-19 13:14:299078 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249079
9080 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499081 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249082
[email protected]f7022f32014-08-21 16:32:199083 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249084 EXPECT_EQ(1, d->response_started_count());
9085 EXPECT_FALSE(d->received_data_before_response());
9086 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9087 }
9088}
9089
[email protected]cde4e80d2009-10-16 19:58:159090// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:129091TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:119092 ASSERT_TRUE(test_server_.Start());
9093
[email protected]6cdfd7f2013-02-08 20:40:159094 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:249095 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
9096 app_path = app_path.AppendASCII("LICENSE");
9097
9098 scoped_ptr<TestDelegate> d(new TestDelegate);
9099 // Set correct login credentials. The delegate will be asked for them when
9100 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589101 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249102 {
[email protected]f7022f32014-08-21 16:32:199103 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9104 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
9105 "wrong_password"),
davidben151423e2015-03-23 18:48:369106 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199107 r->Start();
9108 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249109
[email protected]255620da2013-08-19 13:14:299110 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249111
9112 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499113 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249114
[email protected]f7022f32014-08-21 16:32:199115 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249116 EXPECT_EQ(1, d->response_started_count());
9117 EXPECT_FALSE(d->received_data_before_response());
9118 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9119 }
9120
9121 // Use a new delegate without explicit credentials. The cached ones should be
9122 // used.
9123 d.reset(new TestDelegate);
9124 {
9125 // Don't pass wrong credentials in the URL, they would override valid cached
9126 // ones.
[email protected]f7022f32014-08-21 16:32:199127 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369128 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199129 r->Start();
9130 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249131
[email protected]255620da2013-08-19 13:14:299132 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249133
9134 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499135 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249136
[email protected]f7022f32014-08-21 16:32:199137 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249138 EXPECT_EQ(1, d->response_started_count());
9139 EXPECT_FALSE(d->received_data_before_response());
9140 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9141 }
9142}
[email protected]316c1e5e2012-09-12 15:17:449143#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519144
ttuttlec0c828492015-05-15 01:25:559145TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9146 TestDelegate d;
9147 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9148 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9149 d.set_quit_on_network_start(true);
9150
9151 EXPECT_FALSE(req->response_info().network_accessed);
9152
9153 req->Start();
9154 base::RunLoop().Run();
9155
9156 EXPECT_EQ(1, d.received_before_network_start_count());
9157 EXPECT_EQ(0, d.response_started_count());
9158 EXPECT_FALSE(req->response_info().network_accessed);
9159
9160 req->ResumeNetworkStart();
9161 base::RunLoop().Run();
9162}
9163
9164TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9165 TestDelegate d;
9166 scoped_ptr<URLRequest> req(
9167 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9168
9169 EXPECT_FALSE(req->response_info().network_accessed);
9170
9171 req->Start();
9172 base::RunLoop().Run();
9173
9174 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9175 EXPECT_FALSE(req->response_info().network_accessed);
9176}
9177
9178TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9179 MockHostResolver host_resolver;
9180 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9181 TestURLRequestContext context(true);
9182 context.set_network_delegate(&network_delegate);
9183 context.set_host_resolver(&host_resolver);
9184 host_resolver.rules()->AddSimulatedFailure("*");
9185 context.Init();
9186
9187 TestDelegate d;
9188 scoped_ptr<URLRequest> req(context.CreateRequest(
9189 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9190
9191 EXPECT_FALSE(req->response_info().network_accessed);
9192
9193 req->Start();
9194 base::RunLoop().Run();
9195 EXPECT_TRUE(req->response_info().network_accessed);
9196}
9197
[email protected]7461a402011-03-24 23:19:519198} // namespace net