blob: fdcf71948df21281f11f61a4258d925c1e036554 [file] [log] [blame]
[email protected]9045b8822012-01-13 20:35:351// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit586acc5fe2008-07-26 22:42:524
[email protected]ea224582008-12-07 20:25:465#include "build/build_config.h"
6
[email protected]9396b252008-09-29 17:29:387#if defined(OS_WIN)
[email protected]d8eb84242010-09-25 02:25:068#include <windows.h>
[email protected]aa84a7e2012-03-15 21:29:069#include <shlobj.h>
[email protected]9396b252008-09-29 17:29:3810#endif
11
tbansalea2fb8c2015-05-22 22:23:0012#include <stdint.h>
13
initial.commit586acc5fe2008-07-26 22:42:5214#include <algorithm>
initial.commit586acc5fe2008-07-26 22:42:5215
[email protected]aad63572011-05-24 20:14:3916#include "base/basictypes.h"
[email protected]218aa6a12011-09-13 17:38:3817#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5818#include "base/compiler_specific.h"
mmenke9f2ec60c2015-06-01 20:59:4719#include "base/files/file_path.h"
thestigd8df0332014-09-04 06:33:2920#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0721#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2822#include "base/format_macros.h"
skyostil4891b25b2015-06-11 11:43:4523#include "base/location.h"
mmenke19378d22014-09-09 04:12:5924#include "base/memory/scoped_ptr.h"
[email protected]084262c2011-12-01 21:12:4725#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2226#include "base/message_loop/message_loop.h"
initial.commit586acc5fe2008-07-26 22:42:5227#include "base/path_service.h"
[email protected]255620da2013-08-19 13:14:2928#include "base/run_loop.h"
skyostil4891b25b2015-06-11 11:43:4529#include "base/single_thread_task_runner.h"
[email protected]4dc3ad4f2013-06-11 07:15:5030#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5531#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2232#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2233#include "base/strings/string_util.h"
34#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0535#include "base/strings/utf_string_conversions.h"
tbansalea2fb8c2015-05-22 22:23:0036#include "base/test/histogram_tester.h"
skyostil4891b25b2015-06-11 11:43:4537#include "base/thread_task_runner_handle.h"
mmenkecbc2b712014-10-09 20:29:0738#include "net/base/chunked_upload_data_stream.h"
39#include "net/base/elements_upload_data_stream.h"
initial.commit586acc5fe2008-07-26 22:42:5240#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2541#include "net/base/load_timing_info.h"
42#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0643#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5244#include "net/base/net_module.h"
45#include "net/base/net_util.h"
tbansalea2fb8c2015-05-22 22:23:0046#include "net/base/network_quality.h"
47#include "net/base/network_quality_estimator.h"
[email protected]2ca01e52013-10-31 22:05:1948#include "net/base/request_priority.h"
[email protected]42fdb452012-11-01 12:44:4049#include "net/base/test_data_directory.h"
[email protected]f288ef02012-12-15 20:28:2850#include "net/base/upload_bytes_element_reader.h"
51#include "net/base/upload_data_stream.h"
52#include "net/base/upload_file_element_reader.h"
[email protected]6e7845ae2013-03-29 21:48:1153#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2454#include "net/cert/mock_cert_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1155#include "net/cert/test_root_certs.h"
eromaned744f32015-04-09 06:35:4956#include "net/cert_net/nss_ocsp.h"
[email protected]aa84a7e2012-03-15 21:29:0657#include "net/cookies/cookie_monster.h"
58#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5259#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5360#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3861#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5262#include "net/http/http_cache.h"
63#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1964#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2565#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2166#include "net/http/http_response_headers.h"
[email protected]e50efea2014-03-24 18:41:0067#include "net/http/http_util.h"
eroman87c53d62015-04-02 06:51:0768#include "net/log/net_log.h"
vishal.b62985ca92015-04-17 08:45:5169#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4670#include "net/log/test_net_log_entry.h"
71#include "net/log/test_net_log_util.h"
[email protected]63de95b2008-12-10 04:11:2772#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1973#include "net/socket/ssl_client_socket.h"
davidben8ecc3072014-09-03 23:19:0974#include "net/ssl/ssl_cipher_suite_names.h"
[email protected]536fd0b2013-03-14 17:41:5775#include "net/ssl/ssl_connection_status_flags.h"
[email protected]6e7845ae2013-03-29 21:48:1176#include "net/test/cert_test_util.h"
[email protected]89b32522013-05-07 20:04:2177#include "net/test/spawned_test_server/spawned_test_server.h"
[email protected]e0f35c92013-05-08 16:04:3478#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4379#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5280#include "net/url_request/url_request.h"
[email protected]bcb84f8b2009-08-31 16:20:1481#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:5082#include "net/url_request/url_request_intercepting_job_factory.h"
83#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:4984#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5185#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4786#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4487#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5288#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1589#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:5290
[email protected]02494ec2014-05-07 15:05:2991#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:5592#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:2993#include "net/url_request/file_protocol_handler.h"
94#include "net/url_request/url_request_file_dir_job.h"
95#endif
96
mmenke9f2ec60c2015-06-01 20:59:4797#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
98#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:2999#include "net/url_request/ftp_protocol_handler.h"
100#endif
101
[email protected]dffe8242012-03-20 15:14:27102#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48103#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56104#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27105#include "base/win/windows_version.h"
106#endif
107
[email protected]ad65a3e2013-12-25 18:18:01108using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33109using base::Time;
halton.huoe4e45742014-12-08 07:55:46110using std::string;
[email protected]e1acf6f2008-10-27 20:43:33111
[email protected]7461a402011-03-24 23:19:51112namespace net {
113
initial.commit586acc5fe2008-07-26 22:42:52114namespace {
115
[email protected]42cba2fb2013-03-29 19:58:57116const base::string16 kChrome(ASCIIToUTF16("chrome"));
117const base::string16 kSecret(ASCIIToUTF16("secret"));
118const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44119
mmenke9f2ec60c2015-06-01 20:59:47120const base::FilePath::CharType kTestFilePath[] =
121 FILE_PATH_LITERAL("net/data/url_request_unittest");
122
123#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
124// Test file used in most FTP tests.
125const char kFtpTestFile[] = "BullRunSpeech.txt";
126#endif
127
[email protected]2bba3252013-04-08 19:50:59128// Tests load timing information in the case a fresh connection was used, with
129// no proxy.
[email protected]cba24642014-08-15 20:49:59130void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25131 int connect_timing_flags) {
132 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59133 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25134
135 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
136 EXPECT_FALSE(load_timing_info.request_start.is_null());
137
138 EXPECT_LE(load_timing_info.request_start,
139 load_timing_info.connect_timing.connect_start);
140 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
141 connect_timing_flags);
142 EXPECT_LE(load_timing_info.connect_timing.connect_end,
143 load_timing_info.send_start);
144 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
145 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
146
[email protected]58e32bb2013-01-21 18:23:25147 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
148 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
149}
150
[email protected]2bba3252013-04-08 19:50:59151// Same as above, but with proxy times.
152void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59153 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59154 int connect_timing_flags) {
155 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59156 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59157
158 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
159 EXPECT_FALSE(load_timing_info.request_start.is_null());
160
161 EXPECT_LE(load_timing_info.request_start,
162 load_timing_info.proxy_resolve_start);
163 EXPECT_LE(load_timing_info.proxy_resolve_start,
164 load_timing_info.proxy_resolve_end);
165 EXPECT_LE(load_timing_info.proxy_resolve_end,
166 load_timing_info.connect_timing.connect_start);
167 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
168 connect_timing_flags);
169 EXPECT_LE(load_timing_info.connect_timing.connect_end,
170 load_timing_info.send_start);
171 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
172 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
173}
174
175// Same as above, but with a reused socket and proxy times.
176void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59177 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59178 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59179 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59180
181 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
182 EXPECT_FALSE(load_timing_info.request_start.is_null());
183
184 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
185
186 EXPECT_LE(load_timing_info.request_start,
187 load_timing_info.proxy_resolve_start);
188 EXPECT_LE(load_timing_info.proxy_resolve_start,
189 load_timing_info.proxy_resolve_end);
190 EXPECT_LE(load_timing_info.proxy_resolve_end,
191 load_timing_info.send_start);
192 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
193 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
194}
195
xunjielia6888202015-04-14 21:34:25196#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25197// Tests load timing information in the case of a cache hit, when no cache
198// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17199base::StringPiece TestNetResourceProvider(int key) {
200 return "header";
201}
202
203void FillBuffer(char* buffer, size_t len) {
204 static bool called = false;
205 if (!called) {
206 called = true;
207 int seed = static_cast<int>(Time::Now().ToInternalValue());
208 srand(seed);
209 }
210
211 for (size_t i = 0; i < len; i++) {
212 buffer[i] = static_cast<char>(rand());
213 if (!buffer[i])
214 buffer[i] = 'g';
215 }
216}
xunjielia6888202015-04-14 21:34:25217#endif
[email protected]e3a85452013-11-14 01:46:17218
219#if !defined(OS_IOS)
[email protected]3b23a222013-05-15 21:33:25220void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59221 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25222 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59223 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25224
225 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
226 EXPECT_FALSE(load_timing_info.request_start.is_null());
227
228 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
229 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
230 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
231 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
232
233 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
234 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
235}
236
mmenke9f2ec60c2015-06-01 20:59:47237#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25238// Tests load timing in the case that there is no HTTP response. This can be
239// used to test in the case of errors or non-HTTP requests.
240void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59241 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25242 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59243 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25244
245 // Only the request times should be non-null.
246 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
247 EXPECT_FALSE(load_timing_info.request_start.is_null());
248
249 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
250
251 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
252 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
253 EXPECT_TRUE(load_timing_info.send_start.is_null());
254 EXPECT_TRUE(load_timing_info.send_end.is_null());
255 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
256}
xunjielia6888202015-04-14 21:34:25257#endif
[email protected]58e32bb2013-01-21 18:23:25258
[email protected]71c64f62008-11-15 04:36:51259// Do a case-insensitive search through |haystack| for |needle|.
260bool ContainsString(const std::string& haystack, const char* needle) {
261 std::string::const_iterator it =
262 std::search(haystack.begin(),
263 haystack.end(),
264 needle,
265 needle + strlen(needle),
[email protected]07f1cee2010-11-03 03:53:35266 base::CaseInsensitiveCompare<char>());
[email protected]71c64f62008-11-15 04:36:51267 return it != haystack.end();
268}
269
mmenkecbc2b712014-10-09 20:29:07270scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
[email protected]f288ef02012-12-15 20:28:28271 scoped_ptr<UploadElementReader> reader(
272 new UploadBytesElementReader(data, strlen(data)));
mmenkecbc2b712014-10-09 20:29:07273 return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23274}
275
[email protected]96adadb2010-08-28 01:16:17276// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51277void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17278 // -1 means unknown. 0 means no encryption.
279 EXPECT_GT(ssl_info.security_bits, 0);
280
281 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
pkasting6b68a162014-12-01 22:10:29282 uint16 cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17283 ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29284 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17285}
286
[email protected]79e1fd62013-06-20 06:50:04287void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
288 const GURL& host_url) {
289 std::string sent_value;
290
291 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
292 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
293
294 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
295 EXPECT_EQ("keep-alive", sent_value);
296}
297
[email protected]ede03212012-09-07 12:52:26298bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27299 size_t size = a.size();
300
301 if (size != b.size())
302 return false;
303
304 for (size_t i = 0; i < size; ++i) {
305 if (!a[i].Equals(b[i]))
306 return false;
307 }
308
309 return true;
310}
[email protected]e3a85452013-11-14 01:46:17311#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27312
[email protected]dc5a5cf2012-09-26 02:49:30313// A network delegate that allows the user to choose a subset of request stages
314// to block in. When blocking, the delegate can do one of the following:
315// * synchronously return a pre-specified error code, or
316// * asynchronously return that value via an automatically called callback,
317// or
318// * block and wait for the user to do a callback.
319// Additionally, the user may also specify a redirect URL -- then each request
320// with the current URL different from the redirect target will be redirected
321// to that target, in the on-before-URL-request stage, independent of whether
322// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12323class BlockingNetworkDelegate : public TestNetworkDelegate {
324 public:
[email protected]dc5a5cf2012-09-26 02:49:30325 // Stages in which the delegate can block.
326 enum Stage {
[email protected]9045b8822012-01-13 20:35:35327 NOT_BLOCKED = 0,
328 ON_BEFORE_URL_REQUEST = 1 << 0,
329 ON_BEFORE_SEND_HEADERS = 1 << 1,
330 ON_HEADERS_RECEIVED = 1 << 2,
331 ON_AUTH_REQUIRED = 1 << 3
332 };
333
[email protected]dc5a5cf2012-09-26 02:49:30334 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59335 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30336 enum BlockMode {
337 SYNCHRONOUS, // No callback, returns specified return values.
338 AUTO_CALLBACK, // |this| posts a task to run the callback using the
339 // specified return codes.
340 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
341 // |auth_retval_| are ignored. In every blocking stage the
342 // message loop is quit.
343 };
344
345 // Creates a delegate which does not block at all.
346 explicit BlockingNetworkDelegate(BlockMode block_mode);
347
348 // For users to trigger a callback returning |response|.
349 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
350 // Only call if |block_mode_| == USER_CALLBACK.
351 void DoCallback(int response);
352 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
353
354 // Setters.
355 void set_retval(int retval) {
356 ASSERT_NE(USER_CALLBACK, block_mode_);
357 ASSERT_NE(ERR_IO_PENDING, retval);
358 ASSERT_NE(OK, retval);
359 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35360 }
361
[email protected]dc5a5cf2012-09-26 02:49:30362 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
363 // |auth_credentials_| will be passed with the response.
364 void set_auth_retval(AuthRequiredResponse auth_retval) {
365 ASSERT_NE(USER_CALLBACK, block_mode_);
366 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
367 auth_retval_ = auth_retval;
368 }
369 void set_auth_credentials(const AuthCredentials& auth_credentials) {
370 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35371 }
372
[email protected]dc5a5cf2012-09-26 02:49:30373 void set_redirect_url(const GURL& url) {
374 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35375 }
376
[email protected]dc5a5cf2012-09-26 02:49:30377 void set_block_on(int block_on) {
378 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35379 }
380
[email protected]dc5a5cf2012-09-26 02:49:30381 // Allows the user to check in which state did we block.
382 Stage stage_blocked_for_callback() const {
383 EXPECT_EQ(USER_CALLBACK, block_mode_);
384 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35385 }
386
387 private:
[email protected]dc5a5cf2012-09-26 02:49:30388 void RunCallback(int response, const CompletionCallback& callback);
389 void RunAuthCallback(AuthRequiredResponse response,
390 const AuthCallback& callback);
391
[email protected]9045b8822012-01-13 20:35:35392 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20393 int OnBeforeURLRequest(URLRequest* request,
394 const CompletionCallback& callback,
395 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35396
dchengb03027d2014-10-21 12:00:20397 int OnBeforeSendHeaders(URLRequest* request,
398 const CompletionCallback& callback,
399 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35400
dchengb03027d2014-10-21 12:00:20401 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35402 URLRequest* request,
403 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32404 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16405 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13406 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35407
dchengb03027d2014-10-21 12:00:20408 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35409 URLRequest* request,
410 const AuthChallengeInfo& auth_info,
411 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13412 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35413
[email protected]dc5a5cf2012-09-26 02:49:30414 // Resets the callbacks and |stage_blocked_for_callback_|.
415 void Reset();
[email protected]9045b8822012-01-13 20:35:35416
[email protected]dc5a5cf2012-09-26 02:49:30417 // Checks whether we should block in |stage|. If yes, returns an error code
418 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
419 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
420
421 // Configuration parameters, can be adjusted by public methods:
422 const BlockMode block_mode_;
423
424 // Values returned on blocking stages when mode is SYNCHRONOUS or
425 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
426 int retval_; // To be returned in non-auth stages.
427 AuthRequiredResponse auth_retval_;
428
[email protected]5f714132014-03-26 10:41:16429 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30430 int block_on_; // Bit mask: in which stages to block.
431
432 // |auth_credentials_| will be copied to |*target_auth_credential_| on
433 // callback.
434 AuthCredentials auth_credentials_;
435 AuthCredentials* target_auth_credentials_;
436
437 // Internal variables, not set by not the user:
438 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
439 // USER_CALLBACK).
440 Stage stage_blocked_for_callback_;
441
442 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35443 CompletionCallback callback_;
444 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30445
446 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
447
448 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35449};
450
[email protected]dc5a5cf2012-09-26 02:49:30451BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
452 : block_mode_(block_mode),
453 retval_(OK),
454 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
455 block_on_(0),
456 target_auth_credentials_(NULL),
457 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32458 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30459}
460
461void BlockingNetworkDelegate::DoCallback(int response) {
462 ASSERT_EQ(USER_CALLBACK, block_mode_);
463 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
464 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
465 CompletionCallback callback = callback_;
466 Reset();
467 RunCallback(response, callback);
468}
469
470void BlockingNetworkDelegate::DoAuthCallback(
471 NetworkDelegate::AuthRequiredResponse response) {
472 ASSERT_EQ(USER_CALLBACK, block_mode_);
473 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
474 AuthCallback auth_callback = auth_callback_;
475 Reset();
476 RunAuthCallback(response, auth_callback);
477}
478
479void BlockingNetworkDelegate::RunCallback(int response,
480 const CompletionCallback& callback) {
481 callback.Run(response);
482}
483
484void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
485 const AuthCallback& callback) {
486 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
487 ASSERT_TRUE(target_auth_credentials_ != NULL);
488 *target_auth_credentials_ = auth_credentials_;
489 }
490 callback.Run(response);
491}
492
493int BlockingNetworkDelegate::OnBeforeURLRequest(
494 URLRequest* request,
495 const CompletionCallback& callback,
496 GURL* new_url) {
497 if (redirect_url_ == request->url())
498 return OK; // We've already seen this request and redirected elsewhere.
499
500 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
501
502 if (!redirect_url_.is_empty())
503 *new_url = redirect_url_;
504
505 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
506}
507
508int BlockingNetworkDelegate::OnBeforeSendHeaders(
509 URLRequest* request,
510 const CompletionCallback& callback,
511 HttpRequestHeaders* headers) {
512 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
513
514 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
515}
516
517int BlockingNetworkDelegate::OnHeadersReceived(
518 URLRequest* request,
519 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32520 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16521 scoped_refptr<HttpResponseHeaders>* override_response_headers,
522 GURL* allowed_unsafe_redirect_url) {
523 TestNetworkDelegate::OnHeadersReceived(request,
524 callback,
525 original_response_headers,
526 override_response_headers,
527 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30528
529 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
530}
531
532NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
533 URLRequest* request,
534 const AuthChallengeInfo& auth_info,
535 const AuthCallback& callback,
536 AuthCredentials* credentials) {
537 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
538 credentials);
539 // Check that the user has provided callback for the previous blocked stage.
540 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
541
542 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
543 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
544 }
545
546 target_auth_credentials_ = credentials;
547
548 switch (block_mode_) {
549 case SYNCHRONOUS:
550 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
551 *target_auth_credentials_ = auth_credentials_;
552 return auth_retval_;
553
554 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45555 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30556 FROM_HERE,
557 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
558 weak_factory_.GetWeakPtr(), auth_retval_, callback));
559 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
560
561 case USER_CALLBACK:
562 auth_callback_ = callback;
563 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45564 base::ThreadTaskRunnerHandle::Get()->PostTask(
565 FROM_HERE, base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30566 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
567 }
568 NOTREACHED();
569 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
570}
571
572void BlockingNetworkDelegate::Reset() {
573 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
574 stage_blocked_for_callback_ = NOT_BLOCKED;
575 callback_.Reset();
576 auth_callback_.Reset();
577}
578
579int BlockingNetworkDelegate::MaybeBlockStage(
580 BlockingNetworkDelegate::Stage stage,
581 const CompletionCallback& callback) {
582 // Check that the user has provided callback for the previous blocked stage.
583 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
584
585 if ((block_on_ & stage) == 0) {
586 return OK;
587 }
588
589 switch (block_mode_) {
590 case SYNCHRONOUS:
591 EXPECT_NE(OK, retval_);
592 return retval_;
593
594 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45595 base::ThreadTaskRunnerHandle::Get()->PostTask(
596 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
597 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30598 return ERR_IO_PENDING;
599
600 case USER_CALLBACK:
601 callback_ = callback;
602 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45603 base::ThreadTaskRunnerHandle::Get()->PostTask(
604 FROM_HERE, base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30605 return ERR_IO_PENDING;
606 }
607 NOTREACHED();
608 return 0;
609}
610
[email protected]d5a4dd62012-05-23 01:41:04611class TestURLRequestContextWithProxy : public TestURLRequestContext {
612 public:
613 // Does not own |delegate|.
614 TestURLRequestContextWithProxy(const std::string& proxy,
615 NetworkDelegate* delegate)
616 : TestURLRequestContext(true) {
617 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
618 set_network_delegate(delegate);
619 Init();
620 }
dchengb03027d2014-10-21 12:00:20621 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04622};
623
624} // namespace
625
[email protected]a592c0432012-12-01 18:10:29626// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48627class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00628 public:
[email protected]ef2bf422012-05-11 03:27:09629 URLRequestTest() : default_context_(true) {
630 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25631 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50632 job_factory_impl_ = new URLRequestJobFactoryImpl();
633 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50634 }
bengr1bf8e942014-11-07 01:36:50635
dcheng67be2b1f2014-10-27 21:47:29636 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18637 // URLRequestJobs may post clean-up tasks on destruction.
638 base::RunLoop().RunUntilIdle();
639 }
[email protected]87a09a92011-07-14 15:50:50640
dcheng2339883c2014-12-23 00:23:05641 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50642 SetUpFactory();
643 default_context_.set_job_factory(job_factory_.get());
644 default_context_.Init();
645 PlatformTest::SetUp();
646 }
647
648 virtual void SetUpFactory() {
649 job_factory_impl_->SetProtocolHandler("data", new DataProtocolHandler);
650#if !defined(DISABLE_FILE_SUPPORT)
651 job_factory_impl_->SetProtocolHandler(
skyostil4891b25b2015-06-11 11:43:45652 "file", new FileProtocolHandler(base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50653#endif
654 }
655
656 TestNetworkDelegate* default_network_delegate() {
657 return &default_network_delegate_;
658 }
659
660 const TestURLRequestContext& default_context() const {
661 return default_context_;
662 }
663
664
[email protected]3c5ca8c2011-09-29 01:14:51665 // Adds the TestJobInterceptor to the default context.
666 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23667 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
bengr1bf8e942014-11-07 01:36:50668 job_factory_impl_->SetProtocolHandler("http", NULL);
669 job_factory_impl_->SetProtocolHandler("http", protocol_handler_);
[email protected]f53b4802012-12-20 17:04:23670 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51671 }
672
[email protected]87a09a92011-07-14 15:50:50673 protected:
vishal.b62985ca92015-04-17 08:45:51674 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24675 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50676 URLRequestJobFactoryImpl* job_factory_impl_;
677 scoped_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09678 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48679};
680
[email protected]316c1e5e2012-09-12 15:17:44681TEST_F(URLRequestTest, AboutBlankTest) {
682 TestDelegate d;
683 {
[email protected]f7022f32014-08-21 16:32:19684 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36685 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44686
[email protected]f7022f32014-08-21 16:32:19687 r->Start();
688 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44689
[email protected]255620da2013-08-19 13:14:29690 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44691
[email protected]f7022f32014-08-21 16:32:19692 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44693 EXPECT_FALSE(d.received_data_before_response());
694 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19695 EXPECT_EQ("", r->GetSocketAddress().host());
696 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04697
698 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19699 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44700 }
701}
702
703TEST_F(URLRequestTest, DataURLImageTest) {
704 TestDelegate d;
705 {
706 // Use our nice little Chrome logo.
[email protected]f7022f32014-08-21 16:32:19707 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:19708 GURL(
davidben151423e2015-03-23 18:48:36709 "data:image/png;base64,"
710 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
711 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
712 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
713 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
714 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
715 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
716 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
717 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
718 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
719 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
720 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
721 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
722 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
723 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
724 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
725 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
726 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
727 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
728 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
729 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44730
[email protected]f7022f32014-08-21 16:32:19731 r->Start();
732 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44733
[email protected]255620da2013-08-19 13:14:29734 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44735
[email protected]f7022f32014-08-21 16:32:19736 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44737 EXPECT_FALSE(d.received_data_before_response());
738 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19739 EXPECT_EQ("", r->GetSocketAddress().host());
740 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04741
742 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19743 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44744 }
745}
746
[email protected]5ecf7cb282014-05-11 01:49:55747#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44748TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15749 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44750 PathService::Get(base::FILE_EXE, &app_path);
751 GURL app_url = FilePathToFileURL(app_path);
752
753 TestDelegate d;
754 {
davidben151423e2015-03-23 18:48:36755 scoped_ptr<URLRequest> r(
756 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44757
[email protected]f7022f32014-08-21 16:32:19758 r->Start();
759 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44760
[email protected]255620da2013-08-19 13:14:29761 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44762
763 int64 file_size = -1;
[email protected]56285702013-12-04 18:22:49764 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44765
[email protected]f7022f32014-08-21 16:32:19766 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44767 EXPECT_EQ(1, d.response_started_count());
768 EXPECT_FALSE(d.received_data_before_response());
769 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19770 EXPECT_EQ("", r->GetSocketAddress().host());
771 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04772
773 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19774 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44775 }
776}
777
[email protected]ba40bb762012-12-17 07:11:04778TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15779 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04780 PathService::Get(base::FILE_EXE, &app_path);
781 GURL app_url = FilePathToFileURL(app_path);
782
783 TestDelegate d;
784 {
davidben151423e2015-03-23 18:48:36785 scoped_ptr<URLRequest> r(
786 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04787
[email protected]f7022f32014-08-21 16:32:19788 r->Start();
789 EXPECT_TRUE(r->is_pending());
790 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04791 }
[email protected]79e1fd62013-06-20 06:50:04792 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04793 // destroyed.
[email protected]255620da2013-08-19 13:14:29794 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04795}
796
[email protected]316c1e5e2012-09-12 15:17:44797TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
798 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17799 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44800 FillBuffer(buffer.get(), buffer_size);
801
[email protected]6cdfd7f2013-02-08 20:40:15802 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52803 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44804 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30805 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44806
807 int64 file_size;
[email protected]56285702013-12-04 18:22:49808 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44809
810 const size_t first_byte_position = 500;
811 const size_t last_byte_position = buffer_size - first_byte_position;
812 const size_t content_length = last_byte_position - first_byte_position + 1;
813 std::string partial_buffer_string(buffer.get() + first_byte_position,
814 buffer.get() + last_byte_position + 1);
815
816 TestDelegate d;
817 {
davidben151423e2015-03-23 18:48:36818 scoped_ptr<URLRequest> r(
819 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44820
821 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38822 headers.SetHeader(
823 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59824 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38825 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19826 r->SetExtraRequestHeaders(headers);
827 r->Start();
828 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44829
[email protected]255620da2013-08-19 13:14:29830 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19831 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44832 EXPECT_EQ(1, d.response_started_count());
833 EXPECT_FALSE(d.received_data_before_response());
834 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
835 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
836 EXPECT_TRUE(partial_buffer_string == d.data_received());
837 }
838
[email protected]dd3aa792013-07-16 19:10:23839 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44840}
841
842TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
843 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17844 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44845 FillBuffer(buffer.get(), buffer_size);
846
[email protected]6cdfd7f2013-02-08 20:40:15847 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52848 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44849 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30850 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44851
852 int64 file_size;
[email protected]56285702013-12-04 18:22:49853 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44854
855 const size_t first_byte_position = 500;
856 const size_t last_byte_position = buffer_size - 1;
857 const size_t content_length = last_byte_position - first_byte_position + 1;
858 std::string partial_buffer_string(buffer.get() + first_byte_position,
859 buffer.get() + last_byte_position + 1);
860
861 TestDelegate d;
862 {
davidben151423e2015-03-23 18:48:36863 scoped_ptr<URLRequest> r(
864 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44865
866 HttpRequestHeaders headers;
867 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59868 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38869 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19870 r->SetExtraRequestHeaders(headers);
871 r->Start();
872 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44873
[email protected]255620da2013-08-19 13:14:29874 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19875 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44876 EXPECT_EQ(1, d.response_started_count());
877 EXPECT_FALSE(d.received_data_before_response());
878 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
879 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
880 EXPECT_TRUE(partial_buffer_string == d.data_received());
881 }
882
[email protected]dd3aa792013-07-16 19:10:23883 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44884}
885
886TEST_F(URLRequestTest, FileTestMultipleRanges) {
887 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17888 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44889 FillBuffer(buffer.get(), buffer_size);
890
[email protected]6cdfd7f2013-02-08 20:40:15891 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52892 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44893 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30894 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44895
896 int64 file_size;
[email protected]56285702013-12-04 18:22:49897 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44898
899 TestDelegate d;
900 {
davidben151423e2015-03-23 18:48:36901 scoped_ptr<URLRequest> r(
902 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44903
904 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38905 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19906 r->SetExtraRequestHeaders(headers);
907 r->Start();
908 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44909
[email protected]255620da2013-08-19 13:14:29910 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44911 EXPECT_TRUE(d.request_failed());
912 }
913
[email protected]dd3aa792013-07-16 19:10:23914 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44915}
916
[email protected]3ca8b362013-11-11 22:18:07917TEST_F(URLRequestTest, AllowFileURLs) {
918 base::ScopedTempDir temp_dir;
919 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
920 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52921 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07922 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:30923 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:59924 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:07925
926 {
927 TestDelegate d;
928 TestNetworkDelegate network_delegate;
929 network_delegate.set_can_access_files(true);
930 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36931 scoped_ptr<URLRequest> r(
932 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19933 r->Start();
[email protected]3ca8b362013-11-11 22:18:07934 base::RunLoop().Run();
935 EXPECT_FALSE(d.request_failed());
936 EXPECT_EQ(test_data, d.data_received());
937 }
938
939 {
940 TestDelegate d;
941 TestNetworkDelegate network_delegate;
942 network_delegate.set_can_access_files(false);
943 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36944 scoped_ptr<URLRequest> r(
945 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19946 r->Start();
[email protected]3ca8b362013-11-11 22:18:07947 base::RunLoop().Run();
948 EXPECT_TRUE(d.request_failed());
949 EXPECT_EQ("", d.data_received());
950 }
951}
952
[email protected]316c1e5e2012-09-12 15:17:44953
954TEST_F(URLRequestTest, FileDirCancelTest) {
955 // Put in mock resource provider.
956 NetModule::SetResourceProvider(TestNetResourceProvider);
957
958 TestDelegate d;
959 {
[email protected]6cdfd7f2013-02-08 20:40:15960 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:44961 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
962 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
963 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
964
[email protected]f7022f32014-08-21 16:32:19965 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36966 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19967 req->Start();
968 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44969
970 d.set_cancel_in_received_data_pending(true);
971
[email protected]255620da2013-08-19 13:14:29972 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44973 }
974
975 // Take out mock resource provider.
976 NetModule::SetResourceProvider(NULL);
977}
978
[email protected]5f9581402013-10-30 13:08:32979TEST_F(URLRequestTest, FileDirOutputSanity) {
980 // Verify the general sanity of the the output of the file:
981 // directory lister by checking for the output of a known existing
982 // file.
983 const char sentinel_name[] = "filedir-sentinel";
984
985 base::FilePath path;
986 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:47987 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:32988
989 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:19990 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36991 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19992 req->Start();
[email protected]5f9581402013-10-30 13:08:32993 base::RunLoop().Run();
994
995 // Generate entry for the sentinel file.
996 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:58997 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:49998 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:32999 EXPECT_GT(info.size, 0);
1000 std::string sentinel_output = GetDirectoryListingEntry(
1001 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1002 std::string(sentinel_name),
1003 false /* is_dir */,
1004 info.size,
1005 info.last_modified);
1006
1007 ASSERT_LT(0, d.bytes_received());
1008 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191009 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:321010 // Check for the entry generated for the "sentinel" file.
1011 const std::string& data = d.data_received();
1012 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1013}
1014
[email protected]316c1e5e2012-09-12 15:17:441015TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1016 // There is an implicit redirect when loading a file path that matches a
1017 // directory and does not end with a slash. Ensure that following such
1018 // redirects does not crash. See http://crbug.com/18686.
1019
[email protected]6cdfd7f2013-02-08 20:40:151020 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441021 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471022 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441023
1024 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191025 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361026 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191027 req->Start();
[email protected]255620da2013-08-19 13:14:291028 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441029
1030 ASSERT_EQ(1, d.received_redirect_count());
1031 ASSERT_LT(0, d.bytes_received());
1032 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191033 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441034}
1035
1036#if defined(OS_WIN)
1037// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1038TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1039 TestDelegate d;
davidben151423e2015-03-23 18:48:361040 scoped_ptr<URLRequest> req(
1041 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191042 req->Start();
[email protected]255620da2013-08-19 13:14:291043 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441044
1045 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191046 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441047}
[email protected]5ecf7cb282014-05-11 01:49:551048#endif // defined(OS_WIN)
1049
1050#endif // !defined(DISABLE_FILE_SUPPORT)
1051
1052TEST_F(URLRequestTest, InvalidUrlTest) {
1053 TestDelegate d;
1054 {
[email protected]f7022f32014-08-21 16:32:191055 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361056 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551057
[email protected]f7022f32014-08-21 16:32:191058 r->Start();
1059 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551060
1061 base::RunLoop().Run();
1062 EXPECT_TRUE(d.request_failed());
1063 }
1064}
1065
jochen0e3b3a62014-09-16 18:31:231066TEST_F(URLRequestTest, InvalidReferrerTest) {
1067 TestURLRequestContext context;
1068 TestNetworkDelegate network_delegate;
1069 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1070 context.set_network_delegate(&network_delegate);
1071 TestDelegate d;
davidben151423e2015-03-23 18:48:361072 scoped_ptr<URLRequest> req(
1073 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231074 req->SetReferrer("https://somewhere.com/");
1075
1076 req->Start();
1077 base::RunLoop().Run();
1078 EXPECT_TRUE(d.request_failed());
1079}
1080
[email protected]5ecf7cb282014-05-11 01:49:551081#if defined(OS_WIN)
1082TEST_F(URLRequestTest, ResolveShortcutTest) {
1083 base::FilePath app_path;
1084 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471085 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551086 app_path = app_path.AppendASCII("with-headers.html");
1087
1088 std::wstring lnk_path = app_path.value() + L".lnk";
1089
1090 base::win::ScopedCOMInitializer com_initializer;
1091
1092 // Temporarily create a shortcut for test
1093 {
1094 base::win::ScopedComPtr<IShellLink> shell;
1095 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1096 CLSCTX_INPROC_SERVER)));
1097 base::win::ScopedComPtr<IPersistFile> persist;
1098 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1099 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1100 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1101 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1102 }
1103
1104 TestDelegate d;
1105 {
[email protected]f7022f32014-08-21 16:32:191106 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361107 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551108
[email protected]f7022f32014-08-21 16:32:191109 r->Start();
1110 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551111
1112 base::RunLoop().Run();
1113
1114 WIN32_FILE_ATTRIBUTE_DATA data;
1115 GetFileAttributesEx(app_path.value().c_str(),
1116 GetFileExInfoStandard, &data);
1117 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1118 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1119 FILE_ATTRIBUTE_NORMAL, NULL);
1120 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1121 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1122 DWORD read_size;
1123 BOOL result;
1124 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1125 &read_size, NULL);
1126 std::string content(buffer.get(), read_size);
1127 CloseHandle(file);
1128
[email protected]f7022f32014-08-21 16:32:191129 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551130 EXPECT_EQ(1, d.received_redirect_count());
1131 EXPECT_EQ(content, d.data_received());
1132 }
1133
1134 // Clean the shortcut
1135 DeleteFile(lnk_path.c_str());
1136}
1137#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441138
1139// Custom URLRequestJobs for use with interceptor tests
1140class RestartTestJob : public URLRequestTestJob {
1141 public:
1142 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1143 : URLRequestTestJob(request, network_delegate, true) {}
1144 protected:
dchengb03027d2014-10-21 12:00:201145 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441146 private:
dchengb03027d2014-10-21 12:00:201147 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441148};
1149
1150class CancelTestJob : public URLRequestTestJob {
1151 public:
1152 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1153 : URLRequestTestJob(request, network_delegate, true) {}
1154 protected:
dchengb03027d2014-10-21 12:00:201155 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441156 private:
dchengb03027d2014-10-21 12:00:201157 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441158};
1159
1160class CancelThenRestartTestJob : public URLRequestTestJob {
1161 public:
1162 explicit CancelThenRestartTestJob(URLRequest* request,
1163 NetworkDelegate* network_delegate)
1164 : URLRequestTestJob(request, network_delegate, true) {
1165 }
1166 protected:
dchengb03027d2014-10-21 12:00:201167 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441168 request_->Cancel();
1169 this->NotifyRestartRequired();
1170 }
1171 private:
dchengb03027d2014-10-21 12:00:201172 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441173};
1174
bengr1bf8e942014-11-07 01:36:501175// An Interceptor for use with interceptor tests.
1176class MockURLRequestInterceptor : public URLRequestInterceptor {
1177 public:
1178 // Static getters for canned response header and data strings.
1179 static std::string ok_data() {
1180 return URLRequestTestJob::test_data_1();
1181 }
1182
1183 static std::string ok_headers() {
1184 return URLRequestTestJob::test_headers();
1185 }
1186
1187 static std::string redirect_data() {
1188 return std::string();
1189 }
1190
1191 static std::string redirect_headers() {
1192 return URLRequestTestJob::test_redirect_headers();
1193 }
1194
1195 static std::string error_data() {
1196 return std::string("ohhh nooooo mr. bill!");
1197 }
1198
1199 static std::string error_headers() {
1200 return URLRequestTestJob::test_error_headers();
1201 }
1202
1203 MockURLRequestInterceptor()
1204 : intercept_main_request_(false), restart_main_request_(false),
1205 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1206 simulate_main_network_error_(false),
1207 intercept_redirect_(false), cancel_redirect_request_(false),
1208 intercept_final_response_(false), cancel_final_request_(false),
1209 use_url_request_http_job_(false),
1210 did_intercept_main_(false), did_restart_main_(false),
1211 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1212 did_simulate_error_main_(false),
1213 did_intercept_redirect_(false), did_cancel_redirect_(false),
1214 did_intercept_final_(false), did_cancel_final_(false) {
1215 }
1216
1217 ~MockURLRequestInterceptor() override {
1218 }
1219
1220 // URLRequestInterceptor implementation:
1221 URLRequestJob* MaybeInterceptRequest(
1222 URLRequest* request,
1223 NetworkDelegate* network_delegate) const override {
1224 if (restart_main_request_) {
1225 restart_main_request_ = false;
1226 did_restart_main_ = true;
1227 return new RestartTestJob(request, network_delegate);
1228 }
1229 if (cancel_main_request_) {
1230 cancel_main_request_ = false;
1231 did_cancel_main_ = true;
1232 return new CancelTestJob(request, network_delegate);
1233 }
1234 if (cancel_then_restart_main_request_) {
1235 cancel_then_restart_main_request_ = false;
1236 did_cancel_then_restart_main_ = true;
1237 return new CancelThenRestartTestJob(request, network_delegate);
1238 }
1239 if (simulate_main_network_error_) {
1240 simulate_main_network_error_ = false;
1241 did_simulate_error_main_ = true;
1242 if (use_url_request_http_job_) {
1243 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1244 }
1245 // This job will result in error since the requested URL is not one of the
1246 // URLs supported by these tests.
1247 return new URLRequestTestJob(request, network_delegate, true);
1248 }
1249 if (!intercept_main_request_)
1250 return nullptr;
1251 intercept_main_request_ = false;
1252 did_intercept_main_ = true;
1253 URLRequestTestJob* job = new URLRequestTestJob(request,
1254 network_delegate,
1255 main_headers_,
1256 main_data_,
1257 true);
1258 job->set_load_timing_info(main_request_load_timing_info_);
1259 return job;
1260 }
1261
1262 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1263 NetworkDelegate* network_delegate,
1264 const GURL& location) const override {
1265 if (cancel_redirect_request_) {
1266 cancel_redirect_request_ = false;
1267 did_cancel_redirect_ = true;
1268 return new CancelTestJob(request, network_delegate);
1269 }
1270 if (!intercept_redirect_)
1271 return nullptr;
1272 intercept_redirect_ = false;
1273 did_intercept_redirect_ = true;
1274 if (use_url_request_http_job_) {
1275 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1276 }
1277 return new URLRequestTestJob(request,
1278 network_delegate,
1279 redirect_headers_,
1280 redirect_data_,
1281 true);
1282 }
1283
1284 URLRequestJob* MaybeInterceptResponse(
1285 URLRequest* request,
1286 NetworkDelegate* network_delegate) const override {
1287 if (cancel_final_request_) {
1288 cancel_final_request_ = false;
1289 did_cancel_final_ = true;
1290 return new CancelTestJob(request, network_delegate);
1291 }
1292 if (!intercept_final_response_)
1293 return nullptr;
1294 intercept_final_response_ = false;
1295 did_intercept_final_ = true;
1296 if (use_url_request_http_job_) {
1297 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1298 }
1299 return new URLRequestTestJob(request,
1300 network_delegate,
1301 final_headers_,
1302 final_data_,
1303 true);
1304 }
1305
1306 void set_intercept_main_request(bool intercept_main_request) {
1307 intercept_main_request_ = intercept_main_request;
1308 }
1309
1310 void set_main_headers(const std::string& main_headers) {
1311 main_headers_ = main_headers;
1312 }
1313
1314 void set_main_data(const std::string& main_data) {
1315 main_data_ = main_data;
1316 }
1317
1318 void set_main_request_load_timing_info(
1319 const LoadTimingInfo& main_request_load_timing_info) {
1320 main_request_load_timing_info_ = main_request_load_timing_info;
1321 }
1322
1323 void set_restart_main_request(bool restart_main_request) {
1324 restart_main_request_ = restart_main_request;
1325 }
1326
1327 void set_cancel_main_request(bool cancel_main_request) {
1328 cancel_main_request_ = cancel_main_request;
1329 }
1330
1331 void set_cancel_then_restart_main_request(
1332 bool cancel_then_restart_main_request) {
1333 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1334 }
1335
1336 void set_simulate_main_network_error(bool simulate_main_network_error) {
1337 simulate_main_network_error_ = simulate_main_network_error;
1338 }
1339
1340 void set_intercept_redirect(bool intercept_redirect) {
1341 intercept_redirect_ = intercept_redirect;
1342 }
1343
1344 void set_redirect_headers(const std::string& redirect_headers) {
1345 redirect_headers_ = redirect_headers;
1346 }
1347
1348 void set_redirect_data(const std::string& redirect_data) {
1349 redirect_data_ = redirect_data;
1350 }
1351
1352 void set_cancel_redirect_request(bool cancel_redirect_request) {
1353 cancel_redirect_request_ = cancel_redirect_request;
1354 }
1355
1356 void set_intercept_final_response(bool intercept_final_response) {
1357 intercept_final_response_ = intercept_final_response;
1358 }
1359
1360 void set_final_headers(const std::string& final_headers) {
1361 final_headers_ = final_headers;
1362 }
1363
1364 void set_final_data(const std::string& final_data) {
1365 final_data_ = final_data;
1366 }
1367
1368 void set_cancel_final_request(bool cancel_final_request) {
1369 cancel_final_request_ = cancel_final_request;
1370 }
1371
1372 void set_use_url_request_http_job(bool use_url_request_http_job) {
1373 use_url_request_http_job_ = use_url_request_http_job;
1374 }
1375
1376 bool did_intercept_main() const {
1377 return did_intercept_main_;
1378 }
1379
1380 bool did_restart_main() const {
1381 return did_restart_main_;
1382 }
1383
1384 bool did_cancel_main() const {
1385 return did_cancel_main_;
1386 }
1387
1388 bool did_cancel_then_restart_main() const {
1389 return did_cancel_then_restart_main_;
1390 }
1391
1392 bool did_simulate_error_main() const {
1393 return did_simulate_error_main_;
1394 }
1395
1396 bool did_intercept_redirect() const {
1397 return did_intercept_redirect_;
1398 }
1399
1400 bool did_cancel_redirect() const {
1401 return did_cancel_redirect_;
1402 }
1403
1404 bool did_intercept_final() const {
1405 return did_intercept_final_;
1406 }
1407
1408 bool did_cancel_final() const {
1409 return did_cancel_final_;
1410 }
1411
1412 private:
1413 // Indicate whether to intercept the main request, and if so specify the
1414 // response to return and the LoadTimingInfo to use.
1415 mutable bool intercept_main_request_;
1416 mutable std::string main_headers_;
1417 mutable std::string main_data_;
1418 mutable LoadTimingInfo main_request_load_timing_info_;
1419
1420 // These indicate actions that can be taken within MaybeInterceptRequest.
1421 mutable bool restart_main_request_;
1422 mutable bool cancel_main_request_;
1423 mutable bool cancel_then_restart_main_request_;
1424 mutable bool simulate_main_network_error_;
1425
1426 // Indicate whether to intercept redirects, and if so specify the response to
1427 // return.
1428 mutable bool intercept_redirect_;
1429 mutable std::string redirect_headers_;
1430 mutable std::string redirect_data_;
1431
1432 // Cancel the request within MaybeInterceptRedirect.
1433 mutable bool cancel_redirect_request_;
1434
1435 // Indicate whether to intercept the final response, and if so specify the
1436 // response to return.
1437 mutable bool intercept_final_response_;
1438 mutable std::string final_headers_;
1439 mutable std::string final_data_;
1440
1441 // Cancel the final request within MaybeInterceptResponse.
1442 mutable bool cancel_final_request_;
1443
1444 // Instruct the interceptor to use a real URLRequestHTTPJob.
1445 mutable bool use_url_request_http_job_;
1446
1447 // These indicate if the interceptor did something or not.
1448 mutable bool did_intercept_main_;
1449 mutable bool did_restart_main_;
1450 mutable bool did_cancel_main_;
1451 mutable bool did_cancel_then_restart_main_;
1452 mutable bool did_simulate_error_main_;
1453 mutable bool did_intercept_redirect_;
1454 mutable bool did_cancel_redirect_;
1455 mutable bool did_intercept_final_;
1456 mutable bool did_cancel_final_;
1457};
1458
1459// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1460class URLRequestInterceptorTest : public URLRequestTest {
1461 public:
1462 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1463 }
1464
1465 ~URLRequestInterceptorTest() override {
1466 // URLRequestJobs may post clean-up tasks on destruction.
1467 base::RunLoop().RunUntilIdle();
1468 }
1469
1470 void SetUpFactory() override {
1471 interceptor_ = new MockURLRequestInterceptor();
1472 job_factory_.reset(new URLRequestInterceptingJobFactory(
1473 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1474 }
1475
1476 MockURLRequestInterceptor* interceptor() const {
1477 return interceptor_;
1478 }
1479
1480 private:
1481 MockURLRequestInterceptor* interceptor_;
1482};
1483
1484TEST_F(URLRequestInterceptorTest, Intercept) {
1485 // Intercept the main request and respond with a simple response.
1486 interceptor()->set_intercept_main_request(true);
1487 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1488 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591489 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501490 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361491 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501492 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1493 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1494 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1495 req->SetUserData(nullptr, user_data0);
1496 req->SetUserData(&user_data1, user_data1);
1497 req->SetUserData(&user_data2, user_data2);
1498 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191499 req->Start();
[email protected]255620da2013-08-19 13:14:291500 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591501
bengr1bf8e942014-11-07 01:36:501502 // Make sure we can retrieve our specific user data.
1503 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1504 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1505 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591506
bengr1bf8e942014-11-07 01:36:501507 // Check that we got one good response.
1508 EXPECT_TRUE(req->status().is_success());
1509 EXPECT_EQ(200, req->response_headers()->response_code());
1510 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1511 EXPECT_EQ(1, d.response_started_count());
1512 EXPECT_EQ(0, d.received_redirect_count());
1513}
[email protected]2bba3252013-04-08 19:50:591514
bengr1bf8e942014-11-07 01:36:501515TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1516 // Intercept the main request and respond with a redirect.
1517 interceptor()->set_intercept_main_request(true);
1518 interceptor()->set_main_headers(
1519 MockURLRequestInterceptor::redirect_headers());
1520 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1521
1522 // Intercept that redirect and respond with a final OK response.
1523 interceptor()->set_intercept_redirect(true);
1524 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1525 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1526
1527 TestDelegate d;
1528 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361529 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501530 req->set_method("GET");
1531 req->Start();
1532 base::RunLoop().Run();
1533
1534 // Check that the interceptor got called as expected.
1535 EXPECT_TRUE(interceptor()->did_intercept_main());
1536 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1537
1538 // Check that we got one good response.
1539 EXPECT_TRUE(req->status().is_success());
1540 if (req->status().is_success())
1541 EXPECT_EQ(200, req->response_headers()->response_code());
1542
1543 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1544 EXPECT_EQ(1, d.response_started_count());
1545 EXPECT_EQ(0, d.received_redirect_count());
1546}
1547
1548TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1549 // Intercept the main request to generate a server error response.
1550 interceptor()->set_intercept_main_request(true);
1551 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1552 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1553
1554 // Intercept that error and respond with an OK response.
1555 interceptor()->set_intercept_final_response(true);
1556 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1557 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1558
1559 TestDelegate d;
1560 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361561 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501562 req->set_method("GET");
1563 req->Start();
1564 base::RunLoop().Run();
1565
1566 // Check that the interceptor got called as expected.
1567 EXPECT_TRUE(interceptor()->did_intercept_main());
1568 EXPECT_TRUE(interceptor()->did_intercept_final());
1569
1570 // Check that we got one good response.
1571 EXPECT_TRUE(req->status().is_success());
1572 EXPECT_EQ(200, req->response_headers()->response_code());
1573 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1574 EXPECT_EQ(1, d.response_started_count());
1575 EXPECT_EQ(0, d.received_redirect_count());
1576}
1577
1578TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1579 // Intercept the main request to simulate a network error.
1580 interceptor()->set_simulate_main_network_error(true);
1581
1582 // Intercept that error and respond with an OK response.
1583 interceptor()->set_intercept_final_response(true);
1584 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1585 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1586
1587 TestDelegate d;
1588 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361589 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501590 req->set_method("GET");
1591 req->Start();
1592 base::RunLoop().Run();
1593
1594 // Check that the interceptor got called as expected.
1595 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1596 EXPECT_TRUE(interceptor()->did_intercept_final());
1597
1598 // Check that we received one good response.
1599 EXPECT_TRUE(req->status().is_success());
1600 EXPECT_EQ(200, req->response_headers()->response_code());
1601 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1602 EXPECT_EQ(1, d.response_started_count());
1603 EXPECT_EQ(0, d.received_redirect_count());
1604}
1605
1606TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1607 // Restart the main request.
1608 interceptor()->set_restart_main_request(true);
1609
1610 // then intercept the new main request and respond with an OK response
1611 interceptor()->set_intercept_main_request(true);
1612 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1613 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1614
1615 TestDelegate d;
1616 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361617 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501618 req->set_method("GET");
1619 req->Start();
1620 base::RunLoop().Run();
1621
1622 // Check that the interceptor got called as expected.
1623 EXPECT_TRUE(interceptor()->did_restart_main());
1624 EXPECT_TRUE(interceptor()->did_intercept_main());
1625
1626 // Check that we received one good response.
1627 EXPECT_TRUE(req->status().is_success());
1628 if (req->status().is_success())
1629 EXPECT_EQ(200, req->response_headers()->response_code());
1630
1631 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1632 EXPECT_EQ(1, d.response_started_count());
1633 EXPECT_EQ(0, d.received_redirect_count());
1634}
1635
1636TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1637 // Intercept the main request and cancel from within the restarted job.
1638 interceptor()->set_cancel_main_request(true);
1639
1640 // Set up to intercept the final response and override it with an OK response.
1641 interceptor()->set_intercept_final_response(true);
1642 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1643 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1644
1645 TestDelegate d;
1646 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361647 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501648 req->set_method("GET");
1649 req->Start();
1650 base::RunLoop().Run();
1651
1652 // Check that the interceptor got called as expected.
1653 EXPECT_TRUE(interceptor()->did_cancel_main());
1654 EXPECT_FALSE(interceptor()->did_intercept_final());
1655
1656 // Check that we see a canceled request.
1657 EXPECT_FALSE(req->status().is_success());
1658 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1659}
1660
1661TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1662 // Intercept the main request and respond with a redirect.
1663 interceptor()->set_intercept_main_request(true);
1664 interceptor()->set_main_headers(
1665 MockURLRequestInterceptor::redirect_headers());
1666 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1667
1668 // Intercept the redirect and cancel from within that job.
1669 interceptor()->set_cancel_redirect_request(true);
1670
1671 // Set up to intercept the final response and override it with an OK response.
1672 interceptor()->set_intercept_final_response(true);
1673 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1674 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1675
1676 TestDelegate d;
1677 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361678 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501679 req->set_method("GET");
1680 req->Start();
1681 base::RunLoop().Run();
1682
1683 // Check that the interceptor got called as expected.
1684 EXPECT_TRUE(interceptor()->did_intercept_main());
1685 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1686 EXPECT_FALSE(interceptor()->did_intercept_final());
1687
1688 // Check that we see a canceled request.
1689 EXPECT_FALSE(req->status().is_success());
1690 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1691}
1692
1693TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1694 // Intercept the main request to simulate a network error.
1695 interceptor()->set_simulate_main_network_error(true);
1696
1697 // Set up to intercept final the response and cancel from within that job.
1698 interceptor()->set_cancel_final_request(true);
1699
1700 TestDelegate d;
1701 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361702 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501703 req->set_method("GET");
1704 req->Start();
1705 base::RunLoop().Run();
1706
1707 // Check that the interceptor got called as expected.
1708 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1709 EXPECT_TRUE(interceptor()->did_cancel_final());
1710
1711 // Check that we see a canceled request.
1712 EXPECT_FALSE(req->status().is_success());
1713 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1714}
1715
1716TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1717 // Intercept the main request and cancel then restart from within that job.
1718 interceptor()->set_cancel_then_restart_main_request(true);
1719
1720 // Set up to intercept the final response and override it with an OK response.
1721 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501722 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1723 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501724
1725 TestDelegate d;
1726 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361727 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501728 req->set_method("GET");
1729 req->Start();
1730 base::RunLoop().Run();
1731
1732 // Check that the interceptor got called as expected.
1733 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1734 EXPECT_FALSE(interceptor()->did_intercept_final());
1735
1736 // Check that we see a canceled request.
1737 EXPECT_FALSE(req->status().is_success());
1738 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591739}
1740
1741// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1742// reused. |connect_time_flags| is used to indicate if there should be dns
1743// or SSL times, and |used_proxy| is used for proxy times.
1744LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1745 int connect_time_flags,
1746 bool used_proxy) {
1747 LoadTimingInfo load_timing;
1748 load_timing.socket_log_id = 1;
1749
1750 if (used_proxy) {
1751 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1752 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1753 }
1754
1755 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1756 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1757 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1758 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1759 }
1760 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1761 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1762 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1763 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1764 }
1765 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1766
1767 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1768 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1769 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1770 return load_timing;
1771}
1772
1773// Same as above, but in the case of a reused socket.
1774LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1775 bool used_proxy) {
1776 LoadTimingInfo load_timing;
1777 load_timing.socket_log_id = 1;
1778 load_timing.socket_reused = true;
1779
1780 if (used_proxy) {
1781 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1782 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1783 }
1784
1785 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1786 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1787 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1788 return load_timing;
1789}
1790
bengr1bf8e942014-11-07 01:36:501791LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1792 const LoadTimingInfo& job_load_timing,
1793 const URLRequestContext& context,
1794 MockURLRequestInterceptor* interceptor) {
1795 interceptor->set_intercept_main_request(true);
1796 interceptor->set_main_request_load_timing_info(job_load_timing);
1797 TestDelegate d;
1798 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361799 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501800 req->Start();
1801 base::RunLoop().Run();
1802
1803 LoadTimingInfo resulting_load_timing;
1804 req->GetLoadTimingInfo(&resulting_load_timing);
1805
1806 // None of these should be modified by the URLRequest.
1807 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1808 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1809 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1810 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1811 EXPECT_EQ(job_load_timing.receive_headers_end,
1812 resulting_load_timing.receive_headers_end);
1813
1814 return resulting_load_timing;
1815}
1816
[email protected]2bba3252013-04-08 19:50:591817// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501818TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591819 base::TimeTicks now = base::TimeTicks::Now();
1820 LoadTimingInfo job_load_timing =
1821 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1822
[email protected]2ca01e52013-10-31 22:05:191823 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501824 RunURLRequestInterceptorLoadTimingTest(
1825 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591826
1827 // Nothing should have been changed by the URLRequest.
1828 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1829 load_timing_result.proxy_resolve_start);
1830 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1831 load_timing_result.proxy_resolve_end);
1832 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1833 load_timing_result.connect_timing.dns_start);
1834 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1835 load_timing_result.connect_timing.dns_end);
1836 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1837 load_timing_result.connect_timing.connect_start);
1838 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1839 load_timing_result.connect_timing.connect_end);
1840 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1841 load_timing_result.connect_timing.ssl_start);
1842 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1843 load_timing_result.connect_timing.ssl_end);
1844
1845 // Redundant sanity check.
1846 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1847}
1848
1849// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501850TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591851 base::TimeTicks now = base::TimeTicks::Now();
1852 LoadTimingInfo job_load_timing =
1853 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1854
[email protected]2ca01e52013-10-31 22:05:191855 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501856 RunURLRequestInterceptorLoadTimingTest(
1857 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591858
1859 // Nothing should have been changed by the URLRequest.
1860 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1861 load_timing_result.proxy_resolve_start);
1862 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1863 load_timing_result.proxy_resolve_end);
1864 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1865 load_timing_result.connect_timing.dns_start);
1866 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1867 load_timing_result.connect_timing.dns_end);
1868 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1869 load_timing_result.connect_timing.connect_start);
1870 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1871 load_timing_result.connect_timing.connect_end);
1872 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1873 load_timing_result.connect_timing.ssl_start);
1874 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1875 load_timing_result.connect_timing.ssl_end);
1876
1877 // Redundant sanity check.
1878 TestLoadTimingNotReusedWithProxy(load_timing_result,
1879 CONNECT_TIMING_HAS_SSL_TIMES);
1880}
1881
1882// Make sure that URLRequest correctly adjusts proxy times when they're before
1883// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101884// the case of reusing a SPDY session. The connected socket is not considered
1885// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591886//
1887// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501888TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591889 base::TimeTicks now = base::TimeTicks::Now();
1890 LoadTimingInfo job_load_timing =
1891 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1892 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1893 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1894 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1895 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1896 job_load_timing.connect_timing.connect_start =
1897 now - base::TimeDelta::FromDays(2);
1898 job_load_timing.connect_timing.connect_end =
1899 now - base::TimeDelta::FromDays(1);
1900
[email protected]2ca01e52013-10-31 22:05:191901 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501902 RunURLRequestInterceptorLoadTimingTest(
1903 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591904
1905 // Proxy times, connect times, and DNS times should all be replaced with
1906 // request_start.
1907 EXPECT_EQ(load_timing_result.request_start,
1908 load_timing_result.proxy_resolve_start);
1909 EXPECT_EQ(load_timing_result.request_start,
1910 load_timing_result.proxy_resolve_end);
1911 EXPECT_EQ(load_timing_result.request_start,
1912 load_timing_result.connect_timing.dns_start);
1913 EXPECT_EQ(load_timing_result.request_start,
1914 load_timing_result.connect_timing.dns_end);
1915 EXPECT_EQ(load_timing_result.request_start,
1916 load_timing_result.connect_timing.connect_start);
1917 EXPECT_EQ(load_timing_result.request_start,
1918 load_timing_result.connect_timing.connect_end);
1919
1920 // Other times should have been left null.
1921 TestLoadTimingNotReusedWithProxy(load_timing_result,
1922 CONNECT_TIMING_HAS_DNS_TIMES);
1923}
1924
1925// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:501926TEST_F(URLRequestInterceptorTest,
1927 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:591928 base::TimeTicks now = base::TimeTicks::Now();
1929 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1930 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1931 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1932
[email protected]2ca01e52013-10-31 22:05:191933 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501934 RunURLRequestInterceptorLoadTimingTest(
1935 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591936
1937 // Proxy times and connect times should all be replaced with request_start.
1938 EXPECT_EQ(load_timing_result.request_start,
1939 load_timing_result.proxy_resolve_start);
1940 EXPECT_EQ(load_timing_result.request_start,
1941 load_timing_result.proxy_resolve_end);
1942
1943 // Other times should have been left null.
1944 TestLoadTimingReusedWithProxy(load_timing_result);
1945}
1946
1947// Make sure that URLRequest correctly adjusts connect times when they're before
1948// |request_start|, due to reusing a connected socket. The connected socket is
1949// not considered reused in this test (May be a preconnect).
1950//
1951// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501952TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:591953 base::TimeTicks now = base::TimeTicks::Now();
1954 LoadTimingInfo job_load_timing =
1955 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1956 job_load_timing.connect_timing.connect_start =
1957 now - base::TimeDelta::FromDays(1);
1958 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1959 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1960 job_load_timing.connect_timing.connect_end =
1961 now - base::TimeDelta::FromDays(4);
1962
[email protected]2ca01e52013-10-31 22:05:191963 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501964 RunURLRequestInterceptorLoadTimingTest(
1965 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591966
1967 // Connect times, and SSL times should be replaced with request_start.
1968 EXPECT_EQ(load_timing_result.request_start,
1969 load_timing_result.connect_timing.connect_start);
1970 EXPECT_EQ(load_timing_result.request_start,
1971 load_timing_result.connect_timing.ssl_start);
1972 EXPECT_EQ(load_timing_result.request_start,
1973 load_timing_result.connect_timing.ssl_end);
1974 EXPECT_EQ(load_timing_result.request_start,
1975 load_timing_result.connect_timing.connect_end);
1976
1977 // Other times should have been left null.
1978 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1979}
1980
1981// Make sure that URLRequest correctly adjusts connect times when they're before
1982// |request_start|, due to reusing a connected socket in the case that there
1983// are also proxy times. The connected socket is not considered reused in this
1984// test (May be a preconnect).
1985//
1986// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:501987TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:591988 base::TimeTicks now = base::TimeTicks::Now();
1989 LoadTimingInfo job_load_timing =
1990 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1991 job_load_timing.connect_timing.connect_start =
1992 now - base::TimeDelta::FromDays(1);
1993 job_load_timing.connect_timing.connect_end =
1994 now - base::TimeDelta::FromDays(2);
1995
[email protected]2ca01e52013-10-31 22:05:191996 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501997 RunURLRequestInterceptorLoadTimingTest(
1998 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591999
2000 // Connect times should be replaced with proxy_resolve_end.
2001 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2002 load_timing_result.connect_timing.connect_start);
2003 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2004 load_timing_result.connect_timing.connect_end);
2005
2006 // Other times should have been left null.
2007 TestLoadTimingNotReusedWithProxy(load_timing_result,
2008 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2009}
2010
[email protected]316c1e5e2012-09-12 15:17:442011// Check that two different URL requests have different identifiers.
2012TEST_F(URLRequestTest, Identifiers) {
2013 TestDelegate d;
2014 TestURLRequestContext context;
davidben151423e2015-03-23 18:48:362015 scoped_ptr<URLRequest> req(
2016 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2017 scoped_ptr<URLRequest> other_req(
2018 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442019
mmenke19378d22014-09-09 04:12:592020 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442021}
2022
2023// Check that a failure to connect to the proxy is reported to the network
2024// delegate.
2025TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2026 MockHostResolver host_resolver;
2027 host_resolver.rules()->AddSimulatedFailure("*");
2028
[email protected]ceefd7fd2012-11-29 00:36:242029 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442030 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2031
2032 TestDelegate d;
davidben151423e2015-03-23 18:48:362033 scoped_ptr<URLRequest> req(
2034 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192035 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442036
[email protected]f7022f32014-08-21 16:32:192037 req->Start();
[email protected]255620da2013-08-19 13:14:292038 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442039
2040 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192041 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152042 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192043 EXPECT_TRUE(req->proxy_server().IsEmpty());
2044 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2045 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442046
2047 EXPECT_EQ(1, network_delegate.error_count());
2048 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2049 EXPECT_EQ(1, network_delegate.completed_requests());
2050}
2051
[email protected]cba24642014-08-15 20:49:592052// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442053// content is empty.
2054TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2055 TestDelegate d;
davidben151423e2015-03-23 18:48:362056 scoped_ptr<URLRequest> req(
2057 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192058 req->Start();
[email protected]255620da2013-08-19 13:14:292059 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442060 EXPECT_EQ("", d.data_received());
2061 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2062}
2063
[email protected]5033ab82013-03-22 20:17:462064// Make sure that SetPriority actually sets the URLRequest's priority
2065// correctly, both before and after start.
2066TEST_F(URLRequestTest, SetPriorityBasic) {
2067 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192068 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362069 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192070 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462071
[email protected]f7022f32014-08-21 16:32:192072 req->SetPriority(LOW);
2073 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462074
[email protected]f7022f32014-08-21 16:32:192075 req->Start();
2076 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462077
[email protected]f7022f32014-08-21 16:32:192078 req->SetPriority(MEDIUM);
2079 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462080}
2081
2082// Make sure that URLRequest calls SetPriority on a job before calling
2083// Start on it.
2084TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2085 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192086 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362087 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192088 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462089
2090 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192091 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502092 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462093 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2094
[email protected]f7022f32014-08-21 16:32:192095 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462096
[email protected]f7022f32014-08-21 16:32:192097 req->Start();
[email protected]5033ab82013-03-22 20:17:462098 EXPECT_EQ(LOW, job->priority());
2099}
2100
2101// Make sure that URLRequest passes on its priority updates to its
2102// job.
2103TEST_F(URLRequestTest, SetJobPriority) {
2104 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192105 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362106 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462107
2108 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192109 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502110 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462111
[email protected]f7022f32014-08-21 16:32:192112 req->SetPriority(LOW);
2113 req->Start();
[email protected]5033ab82013-03-22 20:17:462114 EXPECT_EQ(LOW, job->priority());
2115
[email protected]f7022f32014-08-21 16:32:192116 req->SetPriority(MEDIUM);
2117 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462118 EXPECT_EQ(MEDIUM, job->priority());
2119}
2120
[email protected]bb1c4662013-11-14 00:00:072121// Setting the IGNORE_LIMITS load flag should be okay if the priority
2122// is MAXIMUM_PRIORITY.
2123TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2124 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192125 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362126 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192127 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072128
2129 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192130 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]bb1c4662013-11-14 00:00:072131 AddTestInterceptor()->set_main_intercept_job(job.get());
2132
[email protected]f7022f32014-08-21 16:32:192133 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2134 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072135
[email protected]f7022f32014-08-21 16:32:192136 req->SetPriority(MAXIMUM_PRIORITY);
2137 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072138
[email protected]f7022f32014-08-21 16:32:192139 req->Start();
2140 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072141 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2142}
2143
[email protected]ce7d0cbc2013-05-03 18:57:222144// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:442145#if !defined(OS_IOS)
nick5d570de92015-05-04 20:16:162146namespace {
2147
2148// Less verbose way of running a simple testserver for the tests below.
[email protected]ce7d0cbc2013-05-03 18:57:222149class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442150 public:
[email protected]6cdfd7f2013-02-08 20:40:152151 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:222152 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162153 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222154 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:442155 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:222156 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162157 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222158 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:442159};
2160
nick5d570de92015-05-04 20:16:162161} // namespace
2162
[email protected]f2f31b32013-01-16 23:24:092163TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442164 LocalHttpTestServer test_server;
2165 ASSERT_TRUE(test_server.Start());
2166
2167 TestURLRequestContext context;
2168 scoped_refptr<DelayedCookieMonster> delayed_cm =
2169 new DelayedCookieMonster();
2170 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502171 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442172
2173 // Set up a cookie.
2174 {
2175 TestNetworkDelegate network_delegate;
2176 context.set_network_delegate(&network_delegate);
2177 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192178 scoped_ptr<URLRequest> req(context.CreateRequest(
2179 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362180 &d));
[email protected]f7022f32014-08-21 16:32:192181 req->Start();
[email protected]255620da2013-08-19 13:14:292182 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442183 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2184 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2185 EXPECT_EQ(1, network_delegate.set_cookie_count());
2186 }
2187
2188 // Verify that the cookie is set.
2189 {
2190 TestNetworkDelegate network_delegate;
2191 context.set_network_delegate(&network_delegate);
2192 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192193 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:362194 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192195 req->Start();
[email protected]255620da2013-08-19 13:14:292196 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442197
2198 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2199 != std::string::npos);
2200 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2201 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2202 }
2203}
2204
[email protected]f2f31b32013-01-16 23:24:092205TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442206 LocalHttpTestServer test_server;
2207 ASSERT_TRUE(test_server.Start());
2208
2209 // Set up a cookie.
2210 {
2211 TestNetworkDelegate network_delegate;
2212 default_context_.set_network_delegate(&network_delegate);
2213 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192214 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2215 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362216 &d));
[email protected]f7022f32014-08-21 16:32:192217 req->Start();
[email protected]255620da2013-08-19 13:14:292218 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442219 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2220 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2221 }
2222
2223 // Verify that the cookie is set.
2224 {
2225 TestNetworkDelegate network_delegate;
2226 default_context_.set_network_delegate(&network_delegate);
2227 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192228 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362229 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192230 req->Start();
[email protected]255620da2013-08-19 13:14:292231 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442232
2233 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2234 != std::string::npos);
2235 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2236 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2237 }
2238
2239 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2240 {
2241 TestNetworkDelegate network_delegate;
2242 default_context_.set_network_delegate(&network_delegate);
2243 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192244 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362245 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192246 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2247 req->Start();
[email protected]255620da2013-08-19 13:14:292248 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442249
2250 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2251 == std::string::npos);
2252
2253 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2254 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2255 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2256 }
2257}
2258
2259TEST_F(URLRequestTest, DoNotSaveCookies) {
2260 LocalHttpTestServer test_server;
2261 ASSERT_TRUE(test_server.Start());
2262
2263 // Set up a cookie.
2264 {
2265 TestNetworkDelegate network_delegate;
2266 default_context_.set_network_delegate(&network_delegate);
2267 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192268 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2269 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362270 &d));
[email protected]f7022f32014-08-21 16:32:192271 req->Start();
[email protected]255620da2013-08-19 13:14:292272 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442273
2274 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2275 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2276 EXPECT_EQ(1, network_delegate.set_cookie_count());
2277 }
2278
2279 // Try to set-up another cookie and update the previous cookie.
2280 {
2281 TestNetworkDelegate network_delegate;
2282 default_context_.set_network_delegate(&network_delegate);
2283 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192284 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442285 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362286 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192287 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2288 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442289
[email protected]255620da2013-08-19 13:14:292290 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442291
2292 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2293 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2294 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2295 EXPECT_EQ(0, network_delegate.set_cookie_count());
2296 }
2297
2298 // Verify the cookies weren't saved or updated.
2299 {
2300 TestNetworkDelegate network_delegate;
2301 default_context_.set_network_delegate(&network_delegate);
2302 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192303 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362304 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192305 req->Start();
[email protected]255620da2013-08-19 13:14:292306 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442307
2308 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2309 == std::string::npos);
2310 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2311 != std::string::npos);
2312
2313 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2314 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2315 EXPECT_EQ(0, network_delegate.set_cookie_count());
2316 }
2317}
2318
2319TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2320 LocalHttpTestServer test_server;
2321 ASSERT_TRUE(test_server.Start());
2322
2323 // Set up a cookie.
2324 {
2325 TestNetworkDelegate network_delegate;
2326 default_context_.set_network_delegate(&network_delegate);
2327 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192328 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2329 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362330 &d));
[email protected]f7022f32014-08-21 16:32:192331 req->Start();
[email protected]255620da2013-08-19 13:14:292332 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442333
2334 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2335 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2336 }
2337
2338 // Verify that the cookie is set.
2339 {
2340 TestNetworkDelegate network_delegate;
2341 default_context_.set_network_delegate(&network_delegate);
2342 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192343 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362344 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192345 req->Start();
[email protected]255620da2013-08-19 13:14:292346 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442347
2348 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2349 != std::string::npos);
2350
2351 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2352 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2353 }
2354
2355 // Verify that the cookie isn't sent.
2356 {
2357 TestNetworkDelegate network_delegate;
2358 default_context_.set_network_delegate(&network_delegate);
2359 TestDelegate d;
2360 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192361 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362362 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192363 req->Start();
[email protected]255620da2013-08-19 13:14:292364 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442365
2366 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2367 == std::string::npos);
2368
[email protected]22e045f2013-09-20 03:54:032369 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442370 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2371 }
2372}
2373
2374TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2375 LocalHttpTestServer test_server;
2376 ASSERT_TRUE(test_server.Start());
2377
2378 // Set up a cookie.
2379 {
2380 TestNetworkDelegate network_delegate;
2381 default_context_.set_network_delegate(&network_delegate);
2382 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192383 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2384 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362385 &d));
[email protected]f7022f32014-08-21 16:32:192386 req->Start();
[email protected]255620da2013-08-19 13:14:292387 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442388
2389 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2390 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2391 }
2392
2393 // Try to set-up another cookie and update the previous cookie.
2394 {
2395 TestNetworkDelegate network_delegate;
2396 default_context_.set_network_delegate(&network_delegate);
2397 TestDelegate d;
2398 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192399 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442400 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362401 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192402 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442403
[email protected]255620da2013-08-19 13:14:292404 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442405
2406 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2407 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2408 }
2409
2410 // Verify the cookies weren't saved or updated.
2411 {
2412 TestNetworkDelegate network_delegate;
2413 default_context_.set_network_delegate(&network_delegate);
2414 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192415 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362416 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192417 req->Start();
[email protected]255620da2013-08-19 13:14:292418 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442419
2420 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2421 == std::string::npos);
2422 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2423 != std::string::npos);
2424
2425 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2426 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2427 }
2428}
2429
2430TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2431 LocalHttpTestServer test_server;
2432 ASSERT_TRUE(test_server.Start());
2433
2434 // Set up an empty cookie.
2435 {
2436 TestNetworkDelegate network_delegate;
2437 default_context_.set_network_delegate(&network_delegate);
2438 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192439 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362440 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192441 req->Start();
[email protected]255620da2013-08-19 13:14:292442 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442443
2444 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2445 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2446 EXPECT_EQ(0, network_delegate.set_cookie_count());
2447 }
2448}
2449
2450TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2451 LocalHttpTestServer test_server;
2452 ASSERT_TRUE(test_server.Start());
2453
2454 // Set up a cookie.
2455 {
2456 TestNetworkDelegate network_delegate;
2457 default_context_.set_network_delegate(&network_delegate);
2458 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192459 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2460 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362461 &d));
[email protected]f7022f32014-08-21 16:32:192462 req->Start();
[email protected]255620da2013-08-19 13:14:292463 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442464
2465 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2466 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2467 }
2468
2469 // Verify that the cookie is set.
2470 {
2471 TestNetworkDelegate network_delegate;
2472 default_context_.set_network_delegate(&network_delegate);
2473 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192474 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362475 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192476 req->Start();
[email protected]255620da2013-08-19 13:14:292477 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442478
2479 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2480 != std::string::npos);
2481
2482 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2483 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2484 }
2485
2486 // Verify that the cookie isn't sent.
2487 {
2488 TestNetworkDelegate network_delegate;
2489 default_context_.set_network_delegate(&network_delegate);
2490 TestDelegate d;
2491 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192492 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362493 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192494 req->Start();
[email protected]255620da2013-08-19 13:14:292495 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442496
2497 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2498 == std::string::npos);
2499
[email protected]22e045f2013-09-20 03:54:032500 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442501 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2502 }
2503}
2504
2505TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2506 LocalHttpTestServer test_server;
2507 ASSERT_TRUE(test_server.Start());
2508
2509 // Set up a cookie.
2510 {
2511 TestNetworkDelegate network_delegate;
2512 default_context_.set_network_delegate(&network_delegate);
2513 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192514 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2515 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362516 &d));
[email protected]f7022f32014-08-21 16:32:192517 req->Start();
[email protected]255620da2013-08-19 13:14:292518 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442519
2520 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2521 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2522 }
2523
2524 // Try to set-up another cookie and update the previous cookie.
2525 {
2526 TestNetworkDelegate network_delegate;
2527 default_context_.set_network_delegate(&network_delegate);
2528 TestDelegate d;
2529 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192530 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442531 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362532 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192533 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442534
[email protected]255620da2013-08-19 13:14:292535 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442536
2537 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2538 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2539 }
2540
2541 // Verify the cookies weren't saved or updated.
2542 {
2543 TestNetworkDelegate network_delegate;
2544 default_context_.set_network_delegate(&network_delegate);
2545 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192546 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362547 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192548 req->Start();
[email protected]255620da2013-08-19 13:14:292549 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442550
2551 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2552 == std::string::npos);
2553 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2554 != std::string::npos);
2555
2556 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2557 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2558 }
2559}
2560
mkwst3f3daac2015-02-26 20:15:262561TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2562 LocalHttpTestServer test_server;
2563 ASSERT_TRUE(test_server.Start());
2564
2565 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2566 // LocalHttpTestServer points).
2567 {
2568 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152569 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262570 default_context_.set_network_delegate(&network_delegate);
2571
2572 TestDelegate d;
2573 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2574 test_server.GetURL(
2575 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
davidben151423e2015-03-23 18:48:362576 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262577 req->Start();
2578 base::RunLoop().Run();
2579 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2580 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2581 EXPECT_EQ(1, network_delegate.set_cookie_count());
2582 }
2583
2584 // Verify that the cookie is sent for first-party requests.
2585 {
2586 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152587 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262588 default_context_.set_network_delegate(&network_delegate);
2589 TestDelegate d;
2590 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362591 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472592 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst3f3daac2015-02-26 20:15:262593 req->Start();
2594 base::RunLoop().Run();
2595
2596 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2597 std::string::npos);
2598 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2599 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2600 }
2601
2602 // Verify that the cookie is not-sent for non-first-party requests.
2603 {
2604 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152605 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262606 default_context_.set_network_delegate(&network_delegate);
2607 TestDelegate d;
2608 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362609 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262610 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2611 req->Start();
2612 base::RunLoop().Run();
2613
2614 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2615 std::string::npos);
2616 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2617 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2618 }
2619}
2620
mkwst0513c9d2015-04-01 05:53:152621TEST_F(URLRequestTest, FirstPartyOnlyCookiesDisabled) {
2622 LocalHttpTestServer test_server;
2623 ASSERT_TRUE(test_server.Start());
2624
2625 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2626 // LocalHttpTestServer points).
2627 {
2628 TestNetworkDelegate network_delegate;
2629 network_delegate.set_first_party_only_cookies_enabled(false);
2630 default_context_.set_network_delegate(&network_delegate);
2631
2632 TestDelegate d;
2633 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2634 test_server.GetURL(
2635 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
2636 DEFAULT_PRIORITY, &d));
2637 req->Start();
2638 base::RunLoop().Run();
2639 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2640 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2641 EXPECT_EQ(1, network_delegate.set_cookie_count());
2642 }
2643
2644 // Verify that the cookie is sent for first-party requests.
2645 {
2646 TestNetworkDelegate network_delegate;
2647 network_delegate.set_first_party_only_cookies_enabled(false);
2648 default_context_.set_network_delegate(&network_delegate);
2649 TestDelegate d;
2650 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2651 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472652 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst0513c9d2015-04-01 05:53:152653 req->Start();
2654 base::RunLoop().Run();
2655
2656 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2657 std::string::npos);
2658 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2659 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2660 }
2661
2662 // Verify that the cookie is also sent for non-first-party requests.
2663 {
2664 TestNetworkDelegate network_delegate;
2665 network_delegate.set_first_party_only_cookies_enabled(false);
2666 default_context_.set_network_delegate(&network_delegate);
2667 TestDelegate d;
2668 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2669 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2670 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2671 req->Start();
2672 base::RunLoop().Run();
2673
2674 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2675 std::string::npos);
2676 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2677 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2678 }
2679}
2680
[email protected]5095cd72012-11-01 10:29:162681// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2682// value for the |fixed_date| argument given to the constructor.
2683class FixedDateNetworkDelegate : public TestNetworkDelegate {
2684 public:
2685 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2686 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:202687 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:162688
[email protected]cba24642014-08-15 20:49:592689 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:202690 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592691 URLRequest* request,
2692 const CompletionCallback& callback,
2693 const HttpResponseHeaders* original_response_headers,
2694 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:132695 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:162696
2697 private:
2698 std::string fixed_date_;
2699
2700 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2701};
2702
2703int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592704 URLRequest* request,
2705 const CompletionCallback& callback,
2706 const HttpResponseHeaders* original_response_headers,
2707 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:162708 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:592709 HttpResponseHeaders* new_response_headers =
2710 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:162711
2712 new_response_headers->RemoveHeader("Date");
2713 new_response_headers->AddHeader("Date: " + fixed_date_);
2714
2715 *override_response_headers = new_response_headers;
2716 return TestNetworkDelegate::OnHeadersReceived(request,
2717 callback,
2718 original_response_headers,
[email protected]5f714132014-03-26 10:41:162719 override_response_headers,
2720 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:162721}
2722
2723// Test that cookie expiration times are adjusted for server/client clock
2724// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2725// headers by defaulting to GMT. (crbug.com/135131)
2726TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2727 LocalHttpTestServer test_server;
2728 ASSERT_TRUE(test_server.Start());
2729
2730 // Set up an expired cookie.
2731 {
2732 TestNetworkDelegate network_delegate;
2733 default_context_.set_network_delegate(&network_delegate);
2734 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192735 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192736 test_server.GetURL(
2737 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362738 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192739 req->Start();
[email protected]255620da2013-08-19 13:14:292740 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162741 }
2742 // Verify that the cookie is not set.
2743 {
2744 TestNetworkDelegate network_delegate;
2745 default_context_.set_network_delegate(&network_delegate);
2746 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192747 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362748 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192749 req->Start();
[email protected]255620da2013-08-19 13:14:292750 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162751
2752 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2753 }
2754 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2755 {
2756 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2757 default_context_.set_network_delegate(&network_delegate);
2758 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192759 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192760 test_server.GetURL(
2761 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362762 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192763 req->Start();
[email protected]255620da2013-08-19 13:14:292764 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162765 }
2766 // Verify that the cookie is set.
2767 {
2768 TestNetworkDelegate network_delegate;
2769 default_context_.set_network_delegate(&network_delegate);
2770 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192771 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362772 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192773 req->Start();
[email protected]255620da2013-08-19 13:14:292774 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162775
2776 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2777 }
2778}
2779
2780
[email protected]316c1e5e2012-09-12 15:17:442781// Check that it is impossible to change the referrer in the extra headers of
2782// an URLRequest.
2783TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2784 LocalHttpTestServer test_server;
2785 ASSERT_TRUE(test_server.Start());
2786
2787 // If extra headers contain referer and the request contains a referer,
2788 // only the latter shall be respected.
2789 {
2790 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192791 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362792 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192793 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442794
2795 HttpRequestHeaders headers;
2796 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192797 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:442798
[email protected]f7022f32014-08-21 16:32:192799 req->Start();
[email protected]255620da2013-08-19 13:14:292800 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442801
2802 EXPECT_EQ("http://foo.com/", d.data_received());
2803 }
2804
2805 // If extra headers contain a referer but the request does not, no referer
2806 // shall be sent in the header.
2807 {
2808 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192809 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362810 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442811
2812 HttpRequestHeaders headers;
2813 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192814 req->SetExtraRequestHeaders(headers);
2815 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:442816
[email protected]f7022f32014-08-21 16:32:192817 req->Start();
[email protected]255620da2013-08-19 13:14:292818 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442819
2820 EXPECT_EQ("None", d.data_received());
2821 }
2822}
2823
[email protected]b89290212009-08-14 22:37:352824class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112825 public:
mmenke9f2ec60c2015-06-01 20:59:472826 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:112827
[email protected]b89290212009-08-14 22:37:352828 protected:
[email protected]21184962011-10-26 00:50:302829 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2830 // |request_method| is the method to use for the initial request.
2831 // |redirect_method| is the method that is expected to be used for the second
2832 // request, after redirection.
2833 // If |include_data| is true, data is uploaded with the request. The
2834 // response body is expected to match it exactly, if and only if
2835 // |request_method| == |redirect_method|.
2836 void HTTPRedirectMethodTest(const GURL& redirect_url,
2837 const std::string& request_method,
2838 const std::string& redirect_method,
2839 bool include_data) {
2840 static const char kData[] = "hello world";
2841 TestDelegate d;
davidben151423e2015-03-23 18:48:362842 scoped_ptr<URLRequest> req(
2843 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192844 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:302845 if (include_data) {
mmenkecbc2b712014-10-09 20:29:072846 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:302847 HttpRequestHeaders headers;
2848 headers.SetHeader(HttpRequestHeaders::kContentLength,
2849 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:192850 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:302851 }
[email protected]f7022f32014-08-21 16:32:192852 req->Start();
[email protected]255620da2013-08-19 13:14:292853 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:192854 EXPECT_EQ(redirect_method, req->method());
2855 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
2856 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:302857 if (include_data) {
2858 if (request_method == redirect_method) {
2859 EXPECT_EQ(kData, d.data_received());
2860 } else {
2861 EXPECT_NE(kData, d.data_received());
2862 }
2863 }
2864 if (HasFailure())
2865 LOG(WARNING) << "Request method was: " << request_method;
2866 }
2867
jww5fe460ff2015-03-28 00:22:512868 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2869 // |request_method| is the method to use for the initial request.
2870 // |redirect_method| is the method that is expected to be used for the second
2871 // request, after redirection.
2872 // |origin_value| is the expected value for the Origin header after
2873 // redirection. If empty, expects that there will be no Origin header.
2874 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
2875 const std::string& request_method,
2876 const std::string& redirect_method,
2877 const std::string& origin_value) {
2878 TestDelegate d;
2879 scoped_ptr<URLRequest> req(
2880 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
2881 req->set_method(request_method);
2882 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
2883 redirect_url.GetOrigin().spec(), false);
2884 req->Start();
2885
2886 base::RunLoop().Run();
2887
2888 EXPECT_EQ(redirect_method, req->method());
2889 // Note that there is no check for request success here because, for
2890 // purposes of testing, the request very well may fail. For example, if the
2891 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
2892 // origin, there is not an HTTPS server in this unit test framework, so the
2893 // request would fail. However, that's fine, as long as the request headers
2894 // are in order and pass the checks below.
2895 if (origin_value.empty()) {
2896 EXPECT_FALSE(
2897 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
2898 } else {
2899 std::string origin_header;
2900 EXPECT_TRUE(req->extra_request_headers().GetHeader(
2901 HttpRequestHeaders::kOrigin, &origin_header));
2902 EXPECT_EQ(origin_value, origin_header);
2903 }
2904 }
2905
[email protected]762d2db2010-01-11 19:03:012906 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012907 const int kMsgSize = 20000; // multiple of 10
2908 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482909 char* uploadBytes = new char[kMsgSize+1];
2910 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012911 char marker = 'a';
2912 for (int idx = 0; idx < kMsgSize/10; idx++) {
2913 memcpy(ptr, "----------", 10);
2914 ptr += 10;
2915 if (idx % 100 == 0) {
2916 ptr--;
2917 *ptr++ = marker;
2918 if (++marker > 'z')
2919 marker = 'a';
2920 }
2921 }
2922 uploadBytes[kMsgSize] = '\0';
2923
[email protected]762d2db2010-01-11 19:03:012924 for (int i = 0; i < kIterations; ++i) {
2925 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192926 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362927 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192928 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:012929
mmenkecbc2b712014-10-09 20:29:072930 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:012931
[email protected]f7022f32014-08-21 16:32:192932 r->Start();
2933 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:012934
[email protected]255620da2013-08-19 13:14:292935 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:012936
[email protected]329b68b2012-11-14 17:54:272937 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:192938 << "request failed: " << r->status().status()
2939 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:012940
2941 EXPECT_FALSE(d.received_data_before_response());
2942 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:012943 }
2944 delete[] uploadBytes;
2945 }
2946
[email protected]ef2bf422012-05-11 03:27:092947 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:222948 r->AppendChunkToUpload("a", 1, false);
2949 r->AppendChunkToUpload("bcd", 3, false);
2950 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2951 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2952 r->AppendChunkToUpload("0", 1, false);
2953 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:112954 }
2955
[email protected]ef2bf422012-05-11 03:27:092956 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:112957 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:272958 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:112959 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2960
[email protected]329b68b2012-11-14 17:54:272961 ASSERT_EQ(1, d->response_started_count())
2962 << "request failed: " << r->status().status()
2963 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:112964
2965 EXPECT_FALSE(d->received_data_before_response());
2966
[email protected]329b68b2012-11-14 17:54:272967 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2968 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:112969 }
2970
[email protected]ede03212012-09-07 12:52:262971 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:342972 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192973 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2974 test_server_.GetURL("set-many-cookies?" +
davidben151423e2015-03-23 18:48:362975 base::IntToString(num_cookies)),
2976 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:342977
[email protected]f7022f32014-08-21 16:32:192978 r->Start();
2979 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:342980
[email protected]255620da2013-08-19 13:14:292981 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:342982
[email protected]f7022f32014-08-21 16:32:192983 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:342984
[email protected]ede03212012-09-07 12:52:262985 if (!is_success) {
[email protected]f7022f32014-08-21 16:32:192986 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:342987 // The test server appears to be unable to handle subsequent requests
2988 // after this error is triggered. Force it to restart.
2989 EXPECT_TRUE(test_server_.Stop());
2990 EXPECT_TRUE(test_server_.Start());
2991 }
2992
2993 return is_success;
2994 }
2995
bengr1bf8e942014-11-07 01:36:502996 LocalHttpTestServer* test_server() {
2997 return &test_server_;
2998 }
2999
3000 protected:
[email protected]1700c6a2012-02-22 18:07:073001 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353002};
3003
[email protected]95409e12010-08-17 20:07:113004// In this unit test, we're using the HTTPTestServer as a proxy server and
3005// issuing a CONNECT request with the magic host name "www.redirect.com".
3006// The HTTPTestServer will return a 302 response, which we should not
3007// follow.
[email protected]f2f31b32013-01-16 23:24:093008TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:113009 ASSERT_TRUE(test_server_.Start());
3010
[email protected]ceefd7fd2012-11-29 00:36:243011 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043012 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193013 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503014
[email protected]d1ec59082009-02-11 02:48:153015 TestDelegate d;
3016 {
[email protected]f7022f32014-08-21 16:32:193017 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363018 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193019 r->Start();
3020 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153021
[email protected]255620da2013-08-19 13:14:293022 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153023
[email protected]f7022f32014-08-21 16:32:193024 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153025 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193026 EXPECT_TRUE(r->proxy_server().IsEmpty());
3027 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083028 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153029 // We should not have followed the redirect.
3030 EXPECT_EQ(0, d.received_redirect_count());
3031 }
3032}
3033
[email protected]8202d0c2011-02-23 08:31:143034// This is the same as the previous test, but checks that the network delegate
3035// registers the error.
[email protected]c044616e2013-02-20 02:01:263036TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:143037 ASSERT_TRUE(test_server_.Start());
3038
[email protected]ceefd7fd2012-11-29 00:36:243039 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043040 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193041 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503042
[email protected]8202d0c2011-02-23 08:31:143043 TestDelegate d;
3044 {
[email protected]f7022f32014-08-21 16:32:193045 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363046 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193047 r->Start();
3048 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143049
[email protected]255620da2013-08-19 13:14:293050 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143051
[email protected]f7022f32014-08-21 16:32:193052 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153053 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193054 EXPECT_TRUE(r->proxy_server().IsEmpty());
3055 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143056 EXPECT_EQ(1, d.response_started_count());
3057 // We should not have followed the redirect.
3058 EXPECT_EQ(0, d.received_redirect_count());
3059
3060 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053061 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143062 }
3063}
3064
[email protected]dc5a5cf2012-09-26 02:49:303065// Tests that we can block and asynchronously return OK in various stages.
3066TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3067 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3068 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3069 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3070 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3071 };
3072 static const size_t blocking_stages_length = arraysize(blocking_stages);
3073
3074 ASSERT_TRUE(test_server_.Start());
3075
3076 TestDelegate d;
3077 BlockingNetworkDelegate network_delegate(
3078 BlockingNetworkDelegate::USER_CALLBACK);
3079 network_delegate.set_block_on(
3080 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3081 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3082 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3083
3084 TestURLRequestContext context(true);
3085 context.set_network_delegate(&network_delegate);
3086 context.Init();
3087
3088 {
[email protected]f7022f32014-08-21 16:32:193089 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363090 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303091
[email protected]f7022f32014-08-21 16:32:193092 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303093 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293094 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303095 EXPECT_EQ(blocking_stages[i],
3096 network_delegate.stage_blocked_for_callback());
3097 network_delegate.DoCallback(OK);
3098 }
[email protected]255620da2013-08-19 13:14:293099 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193100 EXPECT_EQ(200, r->GetResponseCode());
3101 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303102 EXPECT_EQ(1, network_delegate.created_requests());
3103 EXPECT_EQ(0, network_delegate.destroyed_requests());
3104 }
3105 EXPECT_EQ(1, network_delegate.destroyed_requests());
3106}
3107
[email protected]4c76d7c2011-04-15 19:14:123108// Tests that the network delegate can block and cancel a request.
3109TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
3110 ASSERT_TRUE(test_server_.Start());
3111
3112 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303113 BlockingNetworkDelegate network_delegate(
3114 BlockingNetworkDelegate::AUTO_CALLBACK);
3115 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3116 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123117
[email protected]d5a4dd62012-05-23 01:41:043118 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193119 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503120
[email protected]4c76d7c2011-04-15 19:14:123121 {
[email protected]f7022f32014-08-21 16:32:193122 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363123 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123124
[email protected]f7022f32014-08-21 16:32:193125 r->Start();
[email protected]255620da2013-08-19 13:14:293126 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123127
[email protected]f7022f32014-08-21 16:32:193128 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153129 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193130 EXPECT_TRUE(r->proxy_server().IsEmpty());
3131 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123132 EXPECT_EQ(1, network_delegate.created_requests());
3133 EXPECT_EQ(0, network_delegate.destroyed_requests());
3134 }
3135 EXPECT_EQ(1, network_delegate.destroyed_requests());
3136}
3137
[email protected]b4438d32012-09-27 06:15:303138// Helper function for NetworkDelegateCancelRequestAsynchronously and
3139// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3140// delegate operating in |block_mode| and a request for |url|. It blocks the
3141// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3142void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3143 BlockingNetworkDelegate::Stage stage,
3144 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363145 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303146 BlockingNetworkDelegate network_delegate(block_mode);
3147 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3148 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363149
[email protected]b4438d32012-09-27 06:15:303150 TestURLRequestContext context(true);
3151 context.set_network_delegate(&network_delegate);
3152 context.Init();
[email protected]3cd384c602011-08-31 16:12:363153
3154 {
davidben151423e2015-03-23 18:48:363155 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363156
[email protected]f7022f32014-08-21 16:32:193157 r->Start();
[email protected]255620da2013-08-19 13:14:293158 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363159
[email protected]f7022f32014-08-21 16:32:193160 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153161 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193162 EXPECT_TRUE(r->proxy_server().IsEmpty());
3163 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363164 EXPECT_EQ(1, network_delegate.created_requests());
3165 EXPECT_EQ(0, network_delegate.destroyed_requests());
3166 }
3167 EXPECT_EQ(1, network_delegate.destroyed_requests());
3168}
3169
[email protected]b4438d32012-09-27 06:15:303170// The following 3 tests check that the network delegate can cancel a request
3171// synchronously in various stages of the request.
3172TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
3173 ASSERT_TRUE(test_server_.Start());
3174 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3175 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453176 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303177}
3178
3179TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
3180 ASSERT_TRUE(test_server_.Start());
3181 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3182 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453183 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303184}
3185
3186TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
3187 ASSERT_TRUE(test_server_.Start());
3188 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3189 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453190 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303191}
3192
3193// The following 3 tests check that the network delegate can cancel a request
3194// asynchronously in various stages of the request.
3195TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
3196 ASSERT_TRUE(test_server_.Start());
3197 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3198 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453199 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303200}
3201
3202TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
3203 ASSERT_TRUE(test_server_.Start());
3204 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3205 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453206 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303207}
3208
3209TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
3210 ASSERT_TRUE(test_server_.Start());
3211 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3212 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453213 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303214}
3215
[email protected]4c76d7c2011-04-15 19:14:123216// Tests that the network delegate can block and redirect a request to a new
3217// URL.
3218TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
3219 ASSERT_TRUE(test_server_.Start());
3220
3221 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303222 BlockingNetworkDelegate network_delegate(
3223 BlockingNetworkDelegate::AUTO_CALLBACK);
3224 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:123225 GURL redirect_url(test_server_.GetURL("simple.html"));
3226 network_delegate.set_redirect_url(redirect_url);
3227
[email protected]d5a4dd62012-05-23 01:41:043228 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193229 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503230
[email protected]4c76d7c2011-04-15 19:14:123231 {
[email protected]8f1ac082011-04-19 21:14:133232 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363233 scoped_ptr<URLRequest> r(
3234 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123235
[email protected]6be6fa92014-08-06 23:44:563236 // Quit after hitting the redirect, so can check the headers.
3237 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193238 r->Start();
[email protected]255620da2013-08-19 13:14:293239 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123240
[email protected]6be6fa92014-08-06 23:44:563241 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193242 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3243 EXPECT_EQ(307, r->GetResponseCode());
3244 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563245 std::string location;
[email protected]f7022f32014-08-21 16:32:193246 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3247 &location));
[email protected]6be6fa92014-08-06 23:44:563248 EXPECT_EQ(redirect_url, GURL(location));
3249
3250 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193251 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563252 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193253 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3254 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273255 EXPECT_EQ(
3256 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3257 EXPECT_TRUE(
3258 network_delegate.last_observed_proxy().Equals(
3259 test_server_.host_port_pair()));
3260
[email protected]f7022f32014-08-21 16:32:193261 EXPECT_EQ(0, r->status().error());
3262 EXPECT_EQ(redirect_url, r->url());
3263 EXPECT_EQ(original_url, r->original_url());
3264 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123265 EXPECT_EQ(1, network_delegate.created_requests());
3266 EXPECT_EQ(0, network_delegate.destroyed_requests());
3267 }
3268 EXPECT_EQ(1, network_delegate.destroyed_requests());
3269}
3270
[email protected]b813ed72012-04-05 08:21:363271// Tests that the network delegate can block and redirect a request to a new
3272// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3273TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
3274 ASSERT_TRUE(test_server_.Start());
3275
3276 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303277 BlockingNetworkDelegate network_delegate(
3278 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:363279 GURL redirect_url(test_server_.GetURL("simple.html"));
3280 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363281
[email protected]d5a4dd62012-05-23 01:41:043282 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193283 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363284
3285 {
3286 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363287 scoped_ptr<URLRequest> r(
3288 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363289
[email protected]6be6fa92014-08-06 23:44:563290 // Quit after hitting the redirect, so can check the headers.
3291 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193292 r->Start();
[email protected]255620da2013-08-19 13:14:293293 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363294
[email protected]6be6fa92014-08-06 23:44:563295 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193296 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3297 EXPECT_EQ(307, r->GetResponseCode());
3298 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563299 std::string location;
[email protected]f7022f32014-08-21 16:32:193300 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3301 &location));
[email protected]6be6fa92014-08-06 23:44:563302 EXPECT_EQ(redirect_url, GURL(location));
3303
3304 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193305 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563306 base::RunLoop().Run();
3307
[email protected]f7022f32014-08-21 16:32:193308 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3309 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273310 EXPECT_EQ(
3311 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3312 EXPECT_TRUE(
3313 network_delegate.last_observed_proxy().Equals(
3314 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193315 EXPECT_EQ(0, r->status().error());
3316 EXPECT_EQ(redirect_url, r->url());
3317 EXPECT_EQ(original_url, r->original_url());
3318 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363319 EXPECT_EQ(1, network_delegate.created_requests());
3320 EXPECT_EQ(0, network_delegate.destroyed_requests());
3321 }
3322 EXPECT_EQ(1, network_delegate.destroyed_requests());
3323}
3324
[email protected]3c5ca8c2011-09-29 01:14:513325// Tests that redirects caused by the network delegate preserve POST data.
3326TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3327 ASSERT_TRUE(test_server_.Start());
3328
3329 const char kData[] = "hello world";
3330
3331 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303332 BlockingNetworkDelegate network_delegate(
3333 BlockingNetworkDelegate::AUTO_CALLBACK);
3334 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:513335 GURL redirect_url(test_server_.GetURL("echo"));
3336 network_delegate.set_redirect_url(redirect_url);
3337
[email protected]ef2bf422012-05-11 03:27:093338 TestURLRequestContext context(true);
3339 context.set_network_delegate(&network_delegate);
3340 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513341
3342 {
3343 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363344 scoped_ptr<URLRequest> r(
3345 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193346 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073347 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513348 HttpRequestHeaders headers;
3349 headers.SetHeader(HttpRequestHeaders::kContentLength,
3350 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193351 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563352
3353 // Quit after hitting the redirect, so can check the headers.
3354 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193355 r->Start();
[email protected]255620da2013-08-19 13:14:293356 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513357
[email protected]6be6fa92014-08-06 23:44:563358 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193359 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3360 EXPECT_EQ(307, r->GetResponseCode());
3361 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563362 std::string location;
[email protected]f7022f32014-08-21 16:32:193363 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3364 &location));
[email protected]6be6fa92014-08-06 23:44:563365 EXPECT_EQ(redirect_url, GURL(location));
3366
3367 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193368 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563369 base::RunLoop().Run();
3370
[email protected]f7022f32014-08-21 16:32:193371 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3372 EXPECT_EQ(0, r->status().error());
3373 EXPECT_EQ(redirect_url, r->url());
3374 EXPECT_EQ(original_url, r->original_url());
3375 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513376 EXPECT_EQ(1, network_delegate.created_requests());
3377 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193378 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513379 EXPECT_EQ(kData, d.data_received());
3380 }
3381 EXPECT_EQ(1, network_delegate.destroyed_requests());
3382}
3383
[email protected]5f714132014-03-26 10:41:163384// Tests that the network delegate can block and redirect a request to a new
3385// URL during OnHeadersReceived.
3386TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3387 ASSERT_TRUE(test_server_.Start());
3388
3389 TestDelegate d;
3390 BlockingNetworkDelegate network_delegate(
3391 BlockingNetworkDelegate::AUTO_CALLBACK);
3392 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3393 GURL redirect_url(test_server_.GetURL("simple.html"));
3394 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3395
3396 TestURLRequestContextWithProxy context(
3397 test_server_.host_port_pair().ToString(), &network_delegate);
3398
3399 {
3400 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363401 scoped_ptr<URLRequest> r(
3402 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163403
[email protected]f7022f32014-08-21 16:32:193404 r->Start();
[email protected]5f714132014-03-26 10:41:163405 base::RunLoop().Run();
3406
[email protected]f7022f32014-08-21 16:32:193407 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3408 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273409 EXPECT_EQ(
3410 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3411 EXPECT_TRUE(
3412 network_delegate.last_observed_proxy().Equals(
3413 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193414
3415 EXPECT_EQ(OK, r->status().error());
3416 EXPECT_EQ(redirect_url, r->url());
3417 EXPECT_EQ(original_url, r->original_url());
3418 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163419 EXPECT_EQ(2, network_delegate.created_requests());
3420 EXPECT_EQ(0, network_delegate.destroyed_requests());
3421 }
3422 EXPECT_EQ(1, network_delegate.destroyed_requests());
3423}
3424
[email protected]c2911d72011-10-03 22:16:363425// Tests that the network delegate can synchronously complete OnAuthRequired
3426// by taking no action. This indicates that the NetworkDelegate does not want to
3427// handle the challenge, and is passing the buck along to the
3428// URLRequest::Delegate.
3429TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3430 ASSERT_TRUE(test_server_.Start());
3431
3432 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303433 BlockingNetworkDelegate network_delegate(
3434 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363435
[email protected]ef2bf422012-05-11 03:27:093436 TestURLRequestContext context(true);
3437 context.set_network_delegate(&network_delegate);
3438 context.Init();
[email protected]c2911d72011-10-03 22:16:363439
[email protected]f3cf9802011-10-28 18:44:583440 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363441
3442 {
3443 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363444 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193445 r->Start();
[email protected]79e1fd62013-06-20 06:50:043446
[email protected]255620da2013-08-19 13:14:293447 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043448
[email protected]f7022f32014-08-21 16:32:193449 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3450 EXPECT_EQ(0, r->status().error());
3451 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043452 EXPECT_TRUE(d.auth_required_called());
3453 EXPECT_EQ(1, network_delegate.created_requests());
3454 EXPECT_EQ(0, network_delegate.destroyed_requests());
3455 }
3456 EXPECT_EQ(1, network_delegate.destroyed_requests());
3457}
3458
3459TEST_F(URLRequestTestHTTP,
3460 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3461 ASSERT_TRUE(test_server_.Start());
3462
3463 TestDelegate d;
3464 BlockingNetworkDelegate network_delegate(
3465 BlockingNetworkDelegate::SYNCHRONOUS);
3466
3467 TestURLRequestContext context(true);
3468 context.set_network_delegate(&network_delegate);
3469 context.Init();
3470
3471 d.set_credentials(AuthCredentials(kUser, kSecret));
3472
3473 {
3474 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363475 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193476 r->Start();
[email protected]79e1fd62013-06-20 06:50:043477
3478 {
3479 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193480 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043481 EXPECT_FALSE(headers.HasHeader("Authorization"));
3482 }
3483
[email protected]255620da2013-08-19 13:14:293484 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363485
[email protected]f7022f32014-08-21 16:32:193486 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3487 EXPECT_EQ(0, r->status().error());
3488 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363489 EXPECT_TRUE(d.auth_required_called());
3490 EXPECT_EQ(1, network_delegate.created_requests());
3491 EXPECT_EQ(0, network_delegate.destroyed_requests());
3492 }
3493 EXPECT_EQ(1, network_delegate.destroyed_requests());
3494}
3495
3496// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403497// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363498TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3499 ASSERT_TRUE(test_server_.Start());
3500
3501 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303502 BlockingNetworkDelegate network_delegate(
3503 BlockingNetworkDelegate::SYNCHRONOUS);
3504 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363505 network_delegate.set_auth_retval(
3506 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3507
[email protected]f3cf9802011-10-28 18:44:583508 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363509
[email protected]ef2bf422012-05-11 03:27:093510 TestURLRequestContext context(true);
3511 context.set_network_delegate(&network_delegate);
3512 context.Init();
[email protected]c2911d72011-10-03 22:16:363513
3514 {
3515 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363516 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193517 r->Start();
[email protected]255620da2013-08-19 13:14:293518 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363519
[email protected]f7022f32014-08-21 16:32:193520 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3521 EXPECT_EQ(0, r->status().error());
3522 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363523 EXPECT_FALSE(d.auth_required_called());
3524 EXPECT_EQ(1, network_delegate.created_requests());
3525 EXPECT_EQ(0, network_delegate.destroyed_requests());
3526 }
3527 EXPECT_EQ(1, network_delegate.destroyed_requests());
3528}
3529
[email protected]79e1fd62013-06-20 06:50:043530// Same as above, but also tests that GetFullRequestHeaders returns the proper
3531// headers (for the first or second request) when called at the proper times.
3532TEST_F(URLRequestTestHTTP,
3533 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3534 ASSERT_TRUE(test_server_.Start());
3535
3536 TestDelegate d;
3537 BlockingNetworkDelegate network_delegate(
3538 BlockingNetworkDelegate::SYNCHRONOUS);
3539 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3540 network_delegate.set_auth_retval(
3541 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3542
3543 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3544
3545 TestURLRequestContext context(true);
3546 context.set_network_delegate(&network_delegate);
3547 context.Init();
3548
3549 {
3550 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363551 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193552 r->Start();
[email protected]255620da2013-08-19 13:14:293553 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043554
[email protected]f7022f32014-08-21 16:32:193555 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3556 EXPECT_EQ(0, r->status().error());
3557 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043558 EXPECT_FALSE(d.auth_required_called());
3559 EXPECT_EQ(1, network_delegate.created_requests());
3560 EXPECT_EQ(0, network_delegate.destroyed_requests());
3561
3562 {
3563 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193564 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043565 EXPECT_TRUE(headers.HasHeader("Authorization"));
3566 }
3567 }
3568 EXPECT_EQ(1, network_delegate.destroyed_requests());
3569}
3570
[email protected]c2911d72011-10-03 22:16:363571// Tests that the network delegate can synchronously complete OnAuthRequired
3572// by cancelling authentication.
3573TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3574 ASSERT_TRUE(test_server_.Start());
3575
3576 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303577 BlockingNetworkDelegate network_delegate(
3578 BlockingNetworkDelegate::SYNCHRONOUS);
3579 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363580 network_delegate.set_auth_retval(
3581 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3582
[email protected]ef2bf422012-05-11 03:27:093583 TestURLRequestContext context(true);
3584 context.set_network_delegate(&network_delegate);
3585 context.Init();
[email protected]c2911d72011-10-03 22:16:363586
3587 {
3588 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363589 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193590 r->Start();
[email protected]255620da2013-08-19 13:14:293591 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363592
[email protected]f7022f32014-08-21 16:32:193593 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3594 EXPECT_EQ(OK, r->status().error());
3595 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363596 EXPECT_FALSE(d.auth_required_called());
3597 EXPECT_EQ(1, network_delegate.created_requests());
3598 EXPECT_EQ(0, network_delegate.destroyed_requests());
3599 }
3600 EXPECT_EQ(1, network_delegate.destroyed_requests());
3601}
3602
3603// Tests that the network delegate can asynchronously complete OnAuthRequired
3604// by taking no action. This indicates that the NetworkDelegate does not want
3605// to handle the challenge, and is passing the buck along to the
3606// URLRequest::Delegate.
3607TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3608 ASSERT_TRUE(test_server_.Start());
3609
3610 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303611 BlockingNetworkDelegate network_delegate(
3612 BlockingNetworkDelegate::AUTO_CALLBACK);
3613 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363614
[email protected]ef2bf422012-05-11 03:27:093615 TestURLRequestContext context(true);
3616 context.set_network_delegate(&network_delegate);
3617 context.Init();
[email protected]c2911d72011-10-03 22:16:363618
[email protected]f3cf9802011-10-28 18:44:583619 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363620
3621 {
3622 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363623 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193624 r->Start();
[email protected]255620da2013-08-19 13:14:293625 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363626
[email protected]f7022f32014-08-21 16:32:193627 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3628 EXPECT_EQ(0, r->status().error());
3629 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363630 EXPECT_TRUE(d.auth_required_called());
3631 EXPECT_EQ(1, network_delegate.created_requests());
3632 EXPECT_EQ(0, network_delegate.destroyed_requests());
3633 }
3634 EXPECT_EQ(1, network_delegate.destroyed_requests());
3635}
3636
3637// Tests that the network delegate can asynchronously complete OnAuthRequired
3638// by setting credentials.
3639TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3640 ASSERT_TRUE(test_server_.Start());
3641
3642 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303643 BlockingNetworkDelegate network_delegate(
3644 BlockingNetworkDelegate::AUTO_CALLBACK);
3645 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363646 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363647 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3648
[email protected]f3cf9802011-10-28 18:44:583649 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363650 network_delegate.set_auth_credentials(auth_credentials);
3651
[email protected]ef2bf422012-05-11 03:27:093652 TestURLRequestContext context(true);
3653 context.set_network_delegate(&network_delegate);
3654 context.Init();
[email protected]c2911d72011-10-03 22:16:363655
3656 {
3657 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363658 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193659 r->Start();
[email protected]255620da2013-08-19 13:14:293660 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363661
[email protected]f7022f32014-08-21 16:32:193662 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3663 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:363664
[email protected]f7022f32014-08-21 16:32:193665 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363666 EXPECT_FALSE(d.auth_required_called());
3667 EXPECT_EQ(1, network_delegate.created_requests());
3668 EXPECT_EQ(0, network_delegate.destroyed_requests());
3669 }
3670 EXPECT_EQ(1, network_delegate.destroyed_requests());
3671}
3672
3673// Tests that the network delegate can asynchronously complete OnAuthRequired
3674// by cancelling authentication.
3675TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3676 ASSERT_TRUE(test_server_.Start());
3677
3678 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303679 BlockingNetworkDelegate network_delegate(
3680 BlockingNetworkDelegate::AUTO_CALLBACK);
3681 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363682 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363683 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3684
[email protected]ef2bf422012-05-11 03:27:093685 TestURLRequestContext context(true);
3686 context.set_network_delegate(&network_delegate);
3687 context.Init();
[email protected]c2911d72011-10-03 22:16:363688
3689 {
3690 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363691 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193692 r->Start();
[email protected]255620da2013-08-19 13:14:293693 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363694
[email protected]f7022f32014-08-21 16:32:193695 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3696 EXPECT_EQ(OK, r->status().error());
3697 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363698 EXPECT_FALSE(d.auth_required_called());
3699 EXPECT_EQ(1, network_delegate.created_requests());
3700 EXPECT_EQ(0, network_delegate.destroyed_requests());
3701 }
3702 EXPECT_EQ(1, network_delegate.destroyed_requests());
3703}
3704
[email protected]9045b8822012-01-13 20:35:353705// Tests that we can handle when a network request was canceled while we were
3706// waiting for the network delegate.
3707// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3708TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3709 ASSERT_TRUE(test_server_.Start());
3710
3711 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303712 BlockingNetworkDelegate network_delegate(
3713 BlockingNetworkDelegate::USER_CALLBACK);
3714 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353715
[email protected]ef2bf422012-05-11 03:27:093716 TestURLRequestContext context(true);
3717 context.set_network_delegate(&network_delegate);
3718 context.Init();
[email protected]9045b8822012-01-13 20:35:353719
3720 {
[email protected]f7022f32014-08-21 16:32:193721 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363722 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353723
[email protected]f7022f32014-08-21 16:32:193724 r->Start();
[email protected]255620da2013-08-19 13:14:293725 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303726 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3727 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353728 EXPECT_EQ(0, network_delegate.completed_requests());
3729 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193730 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353731 // Ensure that network delegate is notified.
3732 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193733 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3734 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353735 EXPECT_EQ(1, network_delegate.created_requests());
3736 EXPECT_EQ(0, network_delegate.destroyed_requests());
3737 }
3738 EXPECT_EQ(1, network_delegate.destroyed_requests());
3739}
3740
3741// Tests that we can handle when a network request was canceled while we were
3742// waiting for the network delegate.
3743// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3744TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3745 ASSERT_TRUE(test_server_.Start());
3746
3747 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303748 BlockingNetworkDelegate network_delegate(
3749 BlockingNetworkDelegate::USER_CALLBACK);
3750 network_delegate.set_block_on(
3751 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:353752
[email protected]ef2bf422012-05-11 03:27:093753 TestURLRequestContext context(true);
3754 context.set_network_delegate(&network_delegate);
3755 context.Init();
[email protected]9045b8822012-01-13 20:35:353756
3757 {
[email protected]f7022f32014-08-21 16:32:193758 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363759 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353760
[email protected]f7022f32014-08-21 16:32:193761 r->Start();
[email protected]255620da2013-08-19 13:14:293762 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303763 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3764 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353765 EXPECT_EQ(0, network_delegate.completed_requests());
3766 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193767 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353768 // Ensure that network delegate is notified.
3769 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193770 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3771 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353772 EXPECT_EQ(1, network_delegate.created_requests());
3773 EXPECT_EQ(0, network_delegate.destroyed_requests());
3774 }
3775 EXPECT_EQ(1, network_delegate.destroyed_requests());
3776}
3777
3778// Tests that we can handle when a network request was canceled while we were
3779// waiting for the network delegate.
3780// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3781TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3782 ASSERT_TRUE(test_server_.Start());
3783
3784 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303785 BlockingNetworkDelegate network_delegate(
3786 BlockingNetworkDelegate::USER_CALLBACK);
3787 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:353788
[email protected]ef2bf422012-05-11 03:27:093789 TestURLRequestContext context(true);
3790 context.set_network_delegate(&network_delegate);
3791 context.Init();
[email protected]9045b8822012-01-13 20:35:353792
3793 {
[email protected]f7022f32014-08-21 16:32:193794 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363795 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353796
[email protected]f7022f32014-08-21 16:32:193797 r->Start();
[email protected]255620da2013-08-19 13:14:293798 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303799 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3800 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353801 EXPECT_EQ(0, network_delegate.completed_requests());
3802 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193803 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353804 // Ensure that network delegate is notified.
3805 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193806 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3807 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353808 EXPECT_EQ(1, network_delegate.created_requests());
3809 EXPECT_EQ(0, network_delegate.destroyed_requests());
3810 }
3811 EXPECT_EQ(1, network_delegate.destroyed_requests());
3812}
3813
3814// Tests that we can handle when a network request was canceled while we were
3815// waiting for the network delegate.
3816// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:023817TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:353818 ASSERT_TRUE(test_server_.Start());
3819
3820 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303821 BlockingNetworkDelegate network_delegate(
3822 BlockingNetworkDelegate::USER_CALLBACK);
3823 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:353824
[email protected]ef2bf422012-05-11 03:27:093825 TestURLRequestContext context(true);
3826 context.set_network_delegate(&network_delegate);
3827 context.Init();
[email protected]9045b8822012-01-13 20:35:353828
3829 {
[email protected]f7022f32014-08-21 16:32:193830 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363831 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353832
[email protected]f7022f32014-08-21 16:32:193833 r->Start();
[email protected]255620da2013-08-19 13:14:293834 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303835 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3836 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353837 EXPECT_EQ(0, network_delegate.completed_requests());
3838 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193839 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353840 // Ensure that network delegate is notified.
3841 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193842 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3843 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353844 EXPECT_EQ(1, network_delegate.created_requests());
3845 EXPECT_EQ(0, network_delegate.destroyed_requests());
3846 }
3847 EXPECT_EQ(1, network_delegate.destroyed_requests());
3848}
3849
[email protected]95409e12010-08-17 20:07:113850// In this unit test, we're using the HTTPTestServer as a proxy server and
3851// issuing a CONNECT request with the magic host name "www.server-auth.com".
3852// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:353853TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:113854 ASSERT_TRUE(test_server_.Start());
3855
[email protected]ceefd7fd2012-11-29 00:36:243856 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043857 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193858 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503859
[email protected]dc651782009-02-14 01:45:083860 TestDelegate d;
3861 {
[email protected]f7022f32014-08-21 16:32:193862 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363863 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:083864
[email protected]f7022f32014-08-21 16:32:193865 r->Start();
3866 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:083867
[email protected]255620da2013-08-19 13:14:293868 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:083869
[email protected]f7022f32014-08-21 16:32:193870 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153871 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193872 EXPECT_TRUE(r->proxy_server().IsEmpty());
3873 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083874 }
3875}
3876
[email protected]b89290212009-08-14 22:37:353877TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:113878 ASSERT_TRUE(test_server_.Start());
3879
initial.commit586acc5fe2008-07-26 22:42:523880 TestDelegate d;
3881 {
[email protected]f7022f32014-08-21 16:32:193882 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363883 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:523884
[email protected]f7022f32014-08-21 16:32:193885 r->Start();
3886 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:523887
[email protected]255620da2013-08-19 13:14:293888 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523889
3890 EXPECT_EQ(1, d.response_started_count());
3891 EXPECT_FALSE(d.received_data_before_response());
3892 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193893 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193894 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:193895 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193896 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:163897
[email protected]9e743cd2010-03-16 07:03:533898 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:523899 }
initial.commit586acc5fe2008-07-26 22:42:523900}
3901
[email protected]263163f2012-06-14 22:40:343902// This test has the server send a large number of cookies to the client.
3903// To ensure that no number of cookies causes a crash, a galloping binary
3904// search is used to estimate that maximum number of cookies that are accepted
3905// by the browser. Beyond the maximum number, the request will fail with
3906// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:303907#if defined(OS_WIN)
3908// http://crbug.com/177916
3909#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3910#else
3911#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3912#endif // defined(OS_WIN)
3913TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:343914 ASSERT_TRUE(test_server_.Start());
3915
3916 int lower_bound = 0;
3917 int upper_bound = 1;
3918
3919 // Double the number of cookies until the response header limits are
3920 // exceeded.
3921 while (DoManyCookiesRequest(upper_bound)) {
3922 lower_bound = upper_bound;
3923 upper_bound *= 2;
3924 ASSERT_LT(upper_bound, 1000000);
3925 }
3926
pkasting6b68a162014-12-01 22:10:293927 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:343928 if (tolerance < 2)
3929 tolerance = 2;
3930
3931 // Perform a binary search to find the highest possible number of cookies,
3932 // within the desired tolerance.
3933 while (upper_bound - lower_bound >= tolerance) {
3934 int num_cookies = (lower_bound + upper_bound) / 2;
3935
3936 if (DoManyCookiesRequest(num_cookies))
3937 lower_bound = num_cookies;
3938 else
3939 upper_bound = num_cookies;
3940 }
3941 // Success: the test did not crash.
3942}
3943
[email protected]b89290212009-08-14 22:37:353944TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:113945 ASSERT_TRUE(test_server_.Start());
3946
initial.commit586acc5fe2008-07-26 22:42:523947 TestDelegate d;
3948 {
[email protected]f7022f32014-08-21 16:32:193949 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363950 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:523951
[email protected]f7022f32014-08-21 16:32:193952 r->Start();
3953 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:523954
[email protected]255620da2013-08-19 13:14:293955 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523956
3957 EXPECT_EQ(1, d.response_started_count());
3958 EXPECT_FALSE(d.received_data_before_response());
3959 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193960 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193961 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:193962 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193963 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:523964 }
[email protected]5d7b373e2009-09-02 07:19:033965}
3966
[email protected]79e1fd62013-06-20 06:50:043967TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3968 ASSERT_TRUE(test_server_.Start());
3969
3970 TestDelegate d;
3971 {
3972 GURL test_url(test_server_.GetURL(std::string()));
davidben151423e2015-03-23 18:48:363973 scoped_ptr<URLRequest> r(
3974 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:043975
3976 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193977 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043978
[email protected]f7022f32014-08-21 16:32:193979 r->Start();
3980 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:043981
[email protected]255620da2013-08-19 13:14:293982 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043983
3984 EXPECT_EQ(1, d.response_started_count());
3985 EXPECT_FALSE(d.received_data_before_response());
3986 EXPECT_NE(0, d.bytes_received());
3987 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193988 r->GetSocketAddress().host());
[email protected]79e1fd62013-06-20 06:50:043989 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193990 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:043991
3992 EXPECT_TRUE(d.have_full_request_headers());
3993 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3994 }
3995}
3996
[email protected]58e32bb2013-01-21 18:23:253997TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3998 ASSERT_TRUE(test_server_.Start());
3999
4000 TestDelegate d;
4001 {
[email protected]f7022f32014-08-21 16:32:194002 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364003 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254004
[email protected]f7022f32014-08-21 16:32:194005 r->Start();
4006 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254007
[email protected]255620da2013-08-19 13:14:294008 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254009
4010 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194011 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254012 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4013
4014 EXPECT_EQ(1, d.response_started_count());
4015 EXPECT_FALSE(d.received_data_before_response());
4016 EXPECT_NE(0, d.bytes_received());
4017 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194018 r->GetSocketAddress().host());
[email protected]58e32bb2013-01-21 18:23:254019 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194020 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254021 }
4022}
4023
[email protected]aad63572011-05-24 20:14:394024TEST_F(URLRequestTestHTTP, GetZippedTest) {
4025 ASSERT_TRUE(test_server_.Start());
4026
4027 // Parameter that specifies the Content-Length field in the response:
4028 // C - Compressed length.
4029 // U - Uncompressed length.
4030 // L - Large length (larger than both C & U).
4031 // M - Medium length (between C & U).
4032 // S - Small length (smaller than both C & U).
4033 const char test_parameters[] = "CULMS";
4034 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4035 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444036 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394037 // S has too little data, but we seem to accept it.
4038 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374039 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394040
4041 for (int i = 0; i < num_tests ; i++) {
4042 TestDelegate d;
4043 {
4044 std::string test_file =
4045 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
4046 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394047
[email protected]ceefd7fd2012-11-29 00:36:244048 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094049 TestURLRequestContext context(true);
4050 context.set_network_delegate(&network_delegate);
4051 context.Init();
[email protected]87a09a92011-07-14 15:50:504052
[email protected]f7022f32014-08-21 16:32:194053 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364054 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194055 r->Start();
4056 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394057
[email protected]255620da2013-08-19 13:14:294058 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394059
4060 EXPECT_EQ(1, d.response_started_count());
4061 EXPECT_FALSE(d.received_data_before_response());
4062 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194063 << " status = " << r->status().status()
4064 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394065 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194066 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394067 << " Parameter = \"" << test_file << "\"";
4068 } else {
[email protected]f7022f32014-08-21 16:32:194069 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4070 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394071 << " Parameter = \"" << test_file << "\"";
4072 }
4073 }
4074 }
4075}
4076
tbansala1caf9612015-06-01 20:24:184077TEST_F(URLRequestTestHTTP, NetworkQualityEstimator) {
tbansalea2fb8c2015-05-22 22:23:004078 ASSERT_TRUE(test_server_.Start());
4079 // Enable requests to local host to be used for network quality estimation.
4080 NetworkQualityEstimator estimator(true);
4081
4082 TestDelegate d;
4083 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4084 TestURLRequestContext context(true);
4085 context.set_network_quality_estimator(&estimator);
4086 context.set_network_delegate(&network_delegate);
4087 context.Init();
4088
4089 uint64_t min_transfer_size_in_bytes =
4090 NetworkQualityEstimator::kMinTransferSizeInBytes;
4091 // Create a long enough URL such that response size exceeds network quality
4092 // estimator's minimum transfer size.
4093 std::string url = "echo.html?";
4094 url.append(min_transfer_size_in_bytes, 'x');
4095
4096 scoped_ptr<URLRequest> r(
4097 context.CreateRequest(test_server_.GetURL(url), DEFAULT_PRIORITY, &d));
4098 int sleep_duration_milliseconds = 1;
4099 base::PlatformThread::Sleep(
4100 base::TimeDelta::FromMilliseconds(sleep_duration_milliseconds));
4101 r->Start();
4102
4103 base::RunLoop().Run();
4104
4105 NetworkQuality network_quality =
4106 context.network_quality_estimator()->GetEstimate();
4107 EXPECT_GE(network_quality.fastest_rtt,
4108 base::TimeDelta::FromMilliseconds(sleep_duration_milliseconds));
4109 EXPECT_GT(network_quality.fastest_rtt_confidence, 0);
4110 EXPECT_GT(network_quality.peak_throughput_kbps, uint64_t(0));
4111 EXPECT_GT(network_quality.peak_throughput_kbps_confidence, 0);
4112
4113 // Verify that histograms are not populated. They should populate only when
4114 // there is a change in ConnectionType.
4115 base::HistogramTester histogram_tester;
4116 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 0);
4117 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 0);
4118
4119 NetworkChangeNotifier::NotifyObserversOfConnectionTypeChangeForTests(
4120 NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI);
4121 base::MessageLoop::current()->RunUntilIdle();
4122 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 1);
4123 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 1);
4124}
4125
[email protected]58e32bb2013-01-21 18:23:254126TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
4127 ASSERT_TRUE(test_server_.Start());
4128
[email protected]007b3f82013-04-09 08:46:454129 GURL destination_url = test_server_.GetURL(std::string());
4130 GURL original_url =
4131 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254132 TestDelegate d;
davidben151423e2015-03-23 18:48:364133 scoped_ptr<URLRequest> req(
4134 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194135 req->Start();
[email protected]255620da2013-08-19 13:14:294136 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254137
4138 EXPECT_EQ(1, d.response_started_count());
4139 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194140 EXPECT_EQ(destination_url, req->url());
4141 EXPECT_EQ(original_url, req->original_url());
4142 ASSERT_EQ(2U, req->url_chain().size());
4143 EXPECT_EQ(original_url, req->url_chain()[0]);
4144 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254145
4146 LoadTimingInfo load_timing_info_before_redirect;
4147 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4148 &load_timing_info_before_redirect));
4149 TestLoadTimingNotReused(load_timing_info_before_redirect,
4150 CONNECT_TIMING_HAS_DNS_TIMES);
4151
4152 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194153 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254154 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4155
4156 // Check that a new socket was used on redirect, since the server does not
4157 // supposed keep-alive sockets, and that the times before the redirect are
4158 // before the ones recorded for the second request.
4159 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4160 load_timing_info.socket_log_id);
4161 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4162 load_timing_info.connect_timing.connect_start);
4163}
4164
[email protected]8f1ac082011-04-19 21:14:134165TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
4166 ASSERT_TRUE(test_server_.Start());
4167
[email protected]007b3f82013-04-09 08:46:454168 GURL destination_url = test_server_.GetURL(std::string());
4169 GURL middle_redirect_url =
4170 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:134171 GURL original_url = test_server_.GetURL(
4172 "server-redirect?" + middle_redirect_url.spec());
4173 TestDelegate d;
davidben151423e2015-03-23 18:48:364174 scoped_ptr<URLRequest> req(
4175 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194176 req->Start();
[email protected]255620da2013-08-19 13:14:294177 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134178
4179 EXPECT_EQ(1, d.response_started_count());
4180 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194181 EXPECT_EQ(destination_url, req->url());
4182 EXPECT_EQ(original_url, req->original_url());
4183 ASSERT_EQ(3U, req->url_chain().size());
4184 EXPECT_EQ(original_url, req->url_chain()[0]);
4185 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4186 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134187}
4188
[email protected]abe1c4a2013-10-25 19:28:514189// First and second pieces of information logged by delegates to URLRequests.
4190const char kFirstDelegateInfo[] = "Wonderful delegate";
4191const char kSecondDelegateInfo[] = "Exciting delegate";
4192
4193// Logs delegate information to a URLRequest. The first string is logged
4194// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4195// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4196// another asynchronous call is used to clear the delegate information
4197// before calling a callback. The object then deletes itself.
4198class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4199 public:
4200 typedef base::Callback<void()> Callback;
4201
4202 // Each time delegate information is added to the URLRequest, the resulting
4203 // load state is checked. The expected load state after each request is
4204 // passed in as an argument.
4205 static void Run(URLRequest* url_request,
4206 LoadState expected_first_load_state,
4207 LoadState expected_second_load_state,
4208 LoadState expected_third_load_state,
4209 const Callback& callback) {
4210 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4211 url_request,
4212 expected_first_load_state,
4213 expected_second_load_state,
4214 expected_third_load_state,
4215 callback);
4216 logger->Start();
4217 }
4218
4219 // Checks that the log entries, starting with log_position, contain the
4220 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4221 // recorded. Returns the index of entry after the expected number of
4222 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464223 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514224 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514225 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4226 if (log_position + 3 >= entries.size()) {
4227 ADD_FAILURE() << "Not enough log entries";
4228 return entries.size();
4229 }
4230 std::string delegate_info;
4231 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4232 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4233 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4234 &delegate_info));
4235 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4236
4237 ++log_position;
4238 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4239 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4240
4241 ++log_position;
4242 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4243 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4244 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4245 &delegate_info));
4246 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4247
4248 ++log_position;
4249 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4250 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4251
4252 return log_position + 1;
4253 }
4254
[email protected]1826a402014-01-08 15:40:484255 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4256 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464257 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4258 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484259 log_position =
4260 ExpectLogContainsSomewhereAfter(entries,
4261 log_position,
4262 NetLog::TYPE_URL_REQUEST_DELEGATE,
4263 NetLog::PHASE_BEGIN);
4264 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4265 entries[log_position + 1].type);
4266 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4267 return log_position + 1;
4268 }
4269
[email protected]abe1c4a2013-10-25 19:28:514270 private:
4271 friend class base::RefCounted<AsyncDelegateLogger>;
4272
4273 AsyncDelegateLogger(URLRequest* url_request,
4274 LoadState expected_first_load_state,
4275 LoadState expected_second_load_state,
4276 LoadState expected_third_load_state,
4277 const Callback& callback)
4278 : url_request_(url_request),
4279 expected_first_load_state_(expected_first_load_state),
4280 expected_second_load_state_(expected_second_load_state),
4281 expected_third_load_state_(expected_third_load_state),
4282 callback_(callback) {
4283 }
4284
4285 ~AsyncDelegateLogger() {}
4286
4287 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534288 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514289 LoadStateWithParam load_state = url_request_->GetLoadState();
4290 EXPECT_EQ(expected_first_load_state_, load_state.state);
4291 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454292 base::ThreadTaskRunnerHandle::Get()->PostTask(
4293 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514294 }
4295
4296 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534297 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514298 LoadStateWithParam load_state = url_request_->GetLoadState();
4299 EXPECT_EQ(expected_second_load_state_, load_state.state);
4300 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4301 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4302 } else {
4303 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4304 }
skyostil4891b25b2015-06-11 11:43:454305 base::ThreadTaskRunnerHandle::Get()->PostTask(
4306 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514307 }
4308
4309 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534310 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514311 LoadStateWithParam load_state = url_request_->GetLoadState();
4312 EXPECT_EQ(expected_third_load_state_, load_state.state);
4313 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084314 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514315 callback_.Run();
4316 }
4317
4318 URLRequest* url_request_;
4319 const int expected_first_load_state_;
4320 const int expected_second_load_state_;
4321 const int expected_third_load_state_;
4322 const Callback callback_;
4323
4324 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4325};
4326
4327// NetworkDelegate that logs delegate information before a request is started,
4328// before headers are sent, when headers are read, and when auth information
4329// is requested. Uses AsyncDelegateLogger.
4330class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4331 public:
4332 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204333 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514334
4335 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204336 int OnBeforeURLRequest(URLRequest* request,
4337 const CompletionCallback& callback,
4338 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514339 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4340 return RunCallbackAsynchronously(request, callback);
4341 }
4342
dchengb03027d2014-10-21 12:00:204343 int OnBeforeSendHeaders(URLRequest* request,
4344 const CompletionCallback& callback,
4345 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514346 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4347 return RunCallbackAsynchronously(request, callback);
4348 }
4349
dchengb03027d2014-10-21 12:00:204350 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514351 URLRequest* request,
4352 const CompletionCallback& callback,
4353 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164354 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134355 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164356 TestNetworkDelegate::OnHeadersReceived(request,
4357 callback,
[email protected]abe1c4a2013-10-25 19:28:514358 original_response_headers,
[email protected]5f714132014-03-26 10:41:164359 override_response_headers,
4360 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514361 return RunCallbackAsynchronously(request, callback);
4362 }
4363
dchengb03027d2014-10-21 12:00:204364 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514365 URLRequest* request,
4366 const AuthChallengeInfo& auth_info,
4367 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134368 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514369 AsyncDelegateLogger::Run(
4370 request,
4371 LOAD_STATE_WAITING_FOR_DELEGATE,
4372 LOAD_STATE_WAITING_FOR_DELEGATE,
4373 LOAD_STATE_WAITING_FOR_DELEGATE,
4374 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4375 callback, credentials));
4376 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4377 }
4378
4379 private:
4380 static int RunCallbackAsynchronously(
4381 URLRequest* request,
4382 const CompletionCallback& callback) {
4383 AsyncDelegateLogger::Run(
4384 request,
4385 LOAD_STATE_WAITING_FOR_DELEGATE,
4386 LOAD_STATE_WAITING_FOR_DELEGATE,
4387 LOAD_STATE_WAITING_FOR_DELEGATE,
4388 base::Bind(callback, OK));
4389 return ERR_IO_PENDING;
4390 }
4391
4392 static void SetAuthAndResume(const AuthCallback& callback,
4393 AuthCredentials* credentials) {
4394 *credentials = AuthCredentials(kUser, kSecret);
4395 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4396 }
4397
4398 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4399};
4400
4401// URLRequest::Delegate that logs delegate information when the headers
4402// are received, when each read completes, and during redirects. Uses
4403// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4404//
4405// Inherits from TestDelegate to reuse the TestDelegate code to handle
4406// advancing to the next step in most cases, as well as cancellation.
4407class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4408 public:
4409 enum CancelStage {
4410 NO_CANCEL = 0,
4411 CANCEL_ON_RECEIVED_REDIRECT,
4412 CANCEL_ON_RESPONSE_STARTED,
4413 CANCEL_ON_READ_COMPLETED
4414 };
4415
4416 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4417 : cancel_stage_(cancel_stage) {
4418 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4419 set_cancel_in_received_redirect(true);
4420 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4421 set_cancel_in_response_started(true);
4422 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4423 set_cancel_in_received_data(true);
4424 }
dchengb03027d2014-10-21 12:00:204425 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514426
4427 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204428 void OnReceivedRedirect(URLRequest* request,
4429 const RedirectInfo& redirect_info,
4430 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514431 *defer_redirect = true;
4432 AsyncDelegateLogger::Run(
4433 request,
4434 LOAD_STATE_WAITING_FOR_DELEGATE,
4435 LOAD_STATE_WAITING_FOR_DELEGATE,
4436 LOAD_STATE_WAITING_FOR_DELEGATE,
4437 base::Bind(
4438 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594439 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514440 }
4441
dchengb03027d2014-10-21 12:00:204442 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514443 AsyncDelegateLogger::Run(
4444 request,
4445 LOAD_STATE_WAITING_FOR_DELEGATE,
4446 LOAD_STATE_WAITING_FOR_DELEGATE,
4447 LOAD_STATE_WAITING_FOR_DELEGATE,
4448 base::Bind(
4449 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4450 base::Unretained(this), request));
4451 }
4452
dchengb03027d2014-10-21 12:00:204453 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514454 AsyncDelegateLogger::Run(
4455 request,
4456 LOAD_STATE_IDLE,
4457 LOAD_STATE_IDLE,
4458 LOAD_STATE_IDLE,
4459 base::Bind(
4460 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4461 base::Unretained(this), request, bytes_read));
4462 }
4463
4464 private:
4465 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594466 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514467 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594468 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514469 // FollowDeferredRedirect should not be called after cancellation.
4470 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4471 return;
4472 if (!defer_redirect)
4473 request->FollowDeferredRedirect();
4474 }
4475
4476 void OnResponseStartedLoggingComplete(URLRequest* request) {
4477 // The parent class continues the request.
4478 TestDelegate::OnResponseStarted(request);
4479 }
4480
4481 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4482 // The parent class continues the request.
4483 TestDelegate::OnReadCompleted(request, bytes_read);
4484 }
4485
4486 const CancelStage cancel_stage_;
4487
4488 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4489};
4490
4491// Tests handling of delegate info before a request starts.
4492TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4493 ASSERT_TRUE(test_server_.Start());
4494
4495 TestDelegate request_delegate;
4496 TestURLRequestContext context(true);
4497 context.set_network_delegate(NULL);
4498 context.set_net_log(&net_log_);
4499 context.Init();
4500
4501 {
davidben151423e2015-03-23 18:48:364502 scoped_ptr<URLRequest> r(
4503 context.CreateRequest(test_server_.GetURL("empty.html"),
4504 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194505 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514506 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084507 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514508
4509 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194510 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514511 LOAD_STATE_WAITING_FOR_DELEGATE,
4512 LOAD_STATE_WAITING_FOR_DELEGATE,
4513 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194514 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514515
4516 base::RunLoop().Run();
4517
[email protected]f7022f32014-08-21 16:32:194518 EXPECT_EQ(200, r->GetResponseCode());
4519 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514520 }
4521
mmenke43758e62015-05-04 21:09:464522 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514523 net_log_.GetEntries(&entries);
4524 size_t log_position = ExpectLogContainsSomewhereAfter(
4525 entries,
4526 0,
4527 NetLog::TYPE_DELEGATE_INFO,
4528 NetLog::PHASE_BEGIN);
4529
4530 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4531
4532 // Nothing else should add any delegate info to the request.
4533 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4534 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4535}
4536
4537// Tests handling of delegate info from a network delegate.
4538TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4539 ASSERT_TRUE(test_server_.Start());
4540
4541 TestDelegate request_delegate;
4542 AsyncLoggingNetworkDelegate network_delegate;
4543 TestURLRequestContext context(true);
4544 context.set_network_delegate(&network_delegate);
4545 context.set_net_log(&net_log_);
4546 context.Init();
4547
4548 {
davidben151423e2015-03-23 18:48:364549 scoped_ptr<URLRequest> r(
4550 context.CreateRequest(test_server_.GetURL("simple.html"),
4551 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194552 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514553 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084554 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514555
[email protected]f7022f32014-08-21 16:32:194556 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514557 base::RunLoop().Run();
4558
[email protected]f7022f32014-08-21 16:32:194559 EXPECT_EQ(200, r->GetResponseCode());
4560 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514561 EXPECT_EQ(1, network_delegate.created_requests());
4562 EXPECT_EQ(0, network_delegate.destroyed_requests());
4563 }
4564 EXPECT_EQ(1, network_delegate.destroyed_requests());
4565
4566 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464567 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514568 net_log_.GetEntries(&entries);
4569 for (size_t i = 0; i < 3; ++i) {
4570 log_position = ExpectLogContainsSomewhereAfter(
4571 entries,
4572 log_position + 1,
4573 NetLog::TYPE_URL_REQUEST_DELEGATE,
4574 NetLog::PHASE_BEGIN);
4575
4576 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4577 log_position + 1);
4578
4579 ASSERT_LT(log_position, entries.size());
4580 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4581 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484582
4583 if (i == 1) {
4584 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4585 entries, log_position + 1);
4586 }
[email protected]abe1c4a2013-10-25 19:28:514587 }
4588
4589 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4590 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4591}
4592
4593// Tests handling of delegate info from a network delegate in the case of an
4594// HTTP redirect.
4595TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4596 ASSERT_TRUE(test_server_.Start());
4597
4598 TestDelegate request_delegate;
4599 AsyncLoggingNetworkDelegate network_delegate;
4600 TestURLRequestContext context(true);
4601 context.set_network_delegate(&network_delegate);
4602 context.set_net_log(&net_log_);
4603 context.Init();
4604
4605 {
[email protected]f7022f32014-08-21 16:32:194606 scoped_ptr<URLRequest> r(context.CreateRequest(
4607 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364608 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194609 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514610 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084611 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514612
[email protected]f7022f32014-08-21 16:32:194613 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514614 base::RunLoop().Run();
4615
[email protected]f7022f32014-08-21 16:32:194616 EXPECT_EQ(200, r->GetResponseCode());
4617 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514618 EXPECT_EQ(2, network_delegate.created_requests());
4619 EXPECT_EQ(0, network_delegate.destroyed_requests());
4620 }
4621 EXPECT_EQ(1, network_delegate.destroyed_requests());
4622
4623 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464624 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514625 net_log_.GetEntries(&entries);
4626 // The NetworkDelegate logged information in OnBeforeURLRequest,
4627 // OnBeforeSendHeaders, and OnHeadersReceived.
4628 for (size_t i = 0; i < 3; ++i) {
4629 log_position = ExpectLogContainsSomewhereAfter(
4630 entries,
4631 log_position + 1,
4632 NetLog::TYPE_URL_REQUEST_DELEGATE,
4633 NetLog::PHASE_BEGIN);
4634
4635 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4636 log_position + 1);
4637
4638 ASSERT_LT(log_position, entries.size());
4639 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4640 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484641
4642 if (i == 1) {
4643 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4644 entries, log_position + 1);
4645 }
[email protected]abe1c4a2013-10-25 19:28:514646 }
4647
4648 // The URLRequest::Delegate then gets informed about the redirect.
4649 log_position = ExpectLogContainsSomewhereAfter(
4650 entries,
4651 log_position + 1,
4652 NetLog::TYPE_URL_REQUEST_DELEGATE,
4653 NetLog::PHASE_BEGIN);
4654
4655 // The NetworkDelegate logged information in the same three events as before.
4656 for (size_t i = 0; i < 3; ++i) {
4657 log_position = ExpectLogContainsSomewhereAfter(
4658 entries,
4659 log_position + 1,
4660 NetLog::TYPE_URL_REQUEST_DELEGATE,
4661 NetLog::PHASE_BEGIN);
4662
4663 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4664 log_position + 1);
4665
4666 ASSERT_LT(log_position, entries.size());
4667 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4668 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4669 }
4670
4671 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4672 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4673}
4674
4675// Tests handling of delegate info from a network delegate in the case of HTTP
4676// AUTH.
4677TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4678 ASSERT_TRUE(test_server_.Start());
4679
4680 TestDelegate request_delegate;
4681 AsyncLoggingNetworkDelegate network_delegate;
4682 TestURLRequestContext context(true);
4683 context.set_network_delegate(&network_delegate);
4684 context.set_net_log(&net_log_);
4685 context.Init();
4686
4687 {
davidben151423e2015-03-23 18:48:364688 scoped_ptr<URLRequest> r(
4689 context.CreateRequest(test_server_.GetURL("auth-basic"),
4690 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194691 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514692 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084693 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514694
[email protected]f7022f32014-08-21 16:32:194695 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514696 base::RunLoop().Run();
4697
[email protected]f7022f32014-08-21 16:32:194698 EXPECT_EQ(200, r->GetResponseCode());
4699 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514700 EXPECT_EQ(1, network_delegate.created_requests());
4701 EXPECT_EQ(0, network_delegate.destroyed_requests());
4702 }
4703 EXPECT_EQ(1, network_delegate.destroyed_requests());
4704
4705 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464706 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514707 net_log_.GetEntries(&entries);
4708 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4709 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4710 // OnBeforeURLRequest and OnBeforeSendHeaders.
4711 for (size_t i = 0; i < 6; ++i) {
4712 log_position = ExpectLogContainsSomewhereAfter(
4713 entries,
4714 log_position + 1,
4715 NetLog::TYPE_URL_REQUEST_DELEGATE,
4716 NetLog::PHASE_BEGIN);
4717
4718 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4719 log_position + 1);
4720
4721 ASSERT_LT(log_position, entries.size());
4722 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4723 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484724
4725 if (i == 1) {
4726 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4727 entries, log_position + 1);
4728 }
[email protected]abe1c4a2013-10-25 19:28:514729 }
4730
4731 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4732 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4733}
4734
4735// Tests handling of delegate info from a URLRequest::Delegate.
4736TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4737 ASSERT_TRUE(test_server_.Start());
4738
4739 AsyncLoggingUrlRequestDelegate request_delegate(
4740 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4741 TestURLRequestContext context(true);
4742 context.set_network_delegate(NULL);
4743 context.set_net_log(&net_log_);
4744 context.Init();
4745
4746 {
4747 // A chunked response with delays between chunks is used to make sure that
4748 // attempts by the URLRequest delegate to log information while reading the
4749 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:484750 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:514751 // that it occurs.
[email protected]f7022f32014-08-21 16:32:194752 scoped_ptr<URLRequest> r(context.CreateRequest(
4753 test_server_.GetURL("chunked?waitBetweenChunks=20"), 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
[email protected]1826a402014-01-08 15:40:484766 size_t log_position = 0;
4767
4768 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4769 entries, log_position);
4770
[email protected]abe1c4a2013-10-25 19:28:514771 // The delegate info should only have been logged on header complete. Other
4772 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:484773 log_position =
4774 ExpectLogContainsSomewhereAfter(entries,
4775 log_position + 1,
4776 NetLog::TYPE_URL_REQUEST_DELEGATE,
4777 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:514778
4779 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4780 log_position + 1);
4781
4782 ASSERT_LT(log_position, entries.size());
4783 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4784 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4785
4786 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4787 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4788 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4789 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4790}
4791
4792// Tests handling of delegate info from a URLRequest::Delegate in the case of
4793// an HTTP redirect.
4794TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4795 ASSERT_TRUE(test_server_.Start());
4796
4797 AsyncLoggingUrlRequestDelegate request_delegate(
4798 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4799 TestURLRequestContext context(true);
4800 context.set_network_delegate(NULL);
4801 context.set_net_log(&net_log_);
4802 context.Init();
4803
4804 {
[email protected]f7022f32014-08-21 16:32:194805 scoped_ptr<URLRequest> r(context.CreateRequest(
4806 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364807 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194808 LoadStateWithParam load_state = r->GetLoadState();
4809 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514810 base::RunLoop().Run();
4811
[email protected]f7022f32014-08-21 16:32:194812 EXPECT_EQ(200, r->GetResponseCode());
4813 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514814 }
4815
mmenke43758e62015-05-04 21:09:464816 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514817 net_log_.GetEntries(&entries);
4818
4819 // Delegate info should only have been logged in OnReceivedRedirect and
4820 // OnResponseStarted.
4821 size_t log_position = 0;
4822 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484823 if (i == 0) {
4824 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4825 entries, log_position) + 1;
4826 }
4827
[email protected]abe1c4a2013-10-25 19:28:514828 log_position = ExpectLogContainsSomewhereAfter(
4829 entries,
4830 log_position,
4831 NetLog::TYPE_URL_REQUEST_DELEGATE,
4832 NetLog::PHASE_BEGIN);
4833
4834 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4835 log_position + 1);
4836
4837 ASSERT_LT(log_position, entries.size());
4838 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4839 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4840 }
4841
4842 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4843 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4844 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4845 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4846}
4847
4848// Tests handling of delegate info from a URLRequest::Delegate in the case of
4849// an HTTP redirect, with cancellation at various points.
4850TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4851 ASSERT_TRUE(test_server_.Start());
4852
4853 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4854 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4855 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4856 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4857 };
4858
4859 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4860 ++test_case) {
4861 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4862 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:514863 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:514864 context.set_network_delegate(NULL);
4865 context.set_net_log(&net_log);
4866 context.Init();
4867
4868 {
[email protected]f7022f32014-08-21 16:32:194869 scoped_ptr<URLRequest> r(context.CreateRequest(
4870 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364871 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194872 LoadStateWithParam load_state = r->GetLoadState();
4873 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514874 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194875 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514876 }
4877
mmenke43758e62015-05-04 21:09:464878 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514879 net_log.GetEntries(&entries);
4880
4881 // Delegate info is always logged in both OnReceivedRedirect and
4882 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4883 // OnResponseStarted delegate call is after cancellation, but logging is
4884 // still currently supported in that call.
4885 size_t log_position = 0;
4886 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484887 if (i == 0) {
4888 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4889 entries, log_position) + 1;
4890 }
4891
[email protected]abe1c4a2013-10-25 19:28:514892 log_position = ExpectLogContainsSomewhereAfter(
4893 entries,
4894 log_position,
4895 NetLog::TYPE_URL_REQUEST_DELEGATE,
4896 NetLog::PHASE_BEGIN);
4897
4898 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4899 log_position + 1);
4900
4901 ASSERT_LT(log_position, entries.size());
4902 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4903 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4904 }
4905
4906 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4907 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4908 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4909 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4910 }
4911}
4912
[email protected]847c0fa92012-11-06 16:37:424913namespace {
4914
4915const char kExtraHeader[] = "Allow-Snafu";
4916const char kExtraValue[] = "fubar";
4917
4918class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204919 void OnReceivedRedirect(URLRequest* request,
4920 const RedirectInfo& redirect_info,
4921 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594922 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:424923 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4924 }
4925};
4926
4927} // namespace
4928
4929TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4930 ASSERT_TRUE(test_server_.Start());
4931
4932 GURL destination_url = test_server_.GetURL(
4933 "echoheader?" + std::string(kExtraHeader));
4934 GURL original_url = test_server_.GetURL(
4935 "server-redirect?" + destination_url.spec());
4936 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:364937 scoped_ptr<URLRequest> req(
4938 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194939 req->Start();
[email protected]255620da2013-08-19 13:14:294940 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:424941
4942 std::string value;
[email protected]f7022f32014-08-21 16:32:194943 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:424944 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4945 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:194946 EXPECT_FALSE(req->is_pending());
4947 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:424948 EXPECT_EQ(kExtraValue, d.data_received());
4949}
4950
[email protected]251a1b92012-11-13 11:01:094951namespace {
4952
4953const char kExtraHeaderToRemove[] = "To-Be-Removed";
4954
4955class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204956 void OnReceivedRedirect(URLRequest* request,
4957 const RedirectInfo& redirect_info,
4958 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594959 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:094960 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4961 }
4962};
4963
4964} // namespace
4965
4966TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4967 ASSERT_TRUE(test_server_.Start());
4968
4969 GURL destination_url = test_server_.GetURL(
4970 "echoheader?" + std::string(kExtraHeaderToRemove));
4971 GURL original_url = test_server_.GetURL(
4972 "server-redirect?" + destination_url.spec());
4973 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:364974 scoped_ptr<URLRequest> req(
4975 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194976 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4977 req->Start();
[email protected]255620da2013-08-19 13:14:294978 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:094979
4980 std::string value;
[email protected]f7022f32014-08-21 16:32:194981 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:094982 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:194983 EXPECT_FALSE(req->is_pending());
4984 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:094985 EXPECT_EQ("None", d.data_received());
4986}
4987
[email protected]316c1e5e2012-09-12 15:17:444988TEST_F(URLRequestTestHTTP, CancelTest) {
4989 TestDelegate d;
4990 {
[email protected]f7022f32014-08-21 16:32:194991 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364992 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:444993
[email protected]f7022f32014-08-21 16:32:194994 r->Start();
4995 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444996
[email protected]f7022f32014-08-21 16:32:194997 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:444998
[email protected]255620da2013-08-19 13:14:294999 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445000
5001 // We expect to receive OnResponseStarted even though the request has been
5002 // cancelled.
5003 EXPECT_EQ(1, d.response_started_count());
5004 EXPECT_EQ(0, d.bytes_received());
5005 EXPECT_FALSE(d.received_data_before_response());
5006 }
5007}
5008
5009TEST_F(URLRequestTestHTTP, CancelTest2) {
5010 ASSERT_TRUE(test_server_.Start());
5011
5012 TestDelegate d;
5013 {
[email protected]f7022f32014-08-21 16:32:195014 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365015 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445016
5017 d.set_cancel_in_response_started(true);
5018
[email protected]f7022f32014-08-21 16:32:195019 r->Start();
5020 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445021
[email protected]255620da2013-08-19 13:14:295022 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445023
5024 EXPECT_EQ(1, d.response_started_count());
5025 EXPECT_EQ(0, d.bytes_received());
5026 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195027 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445028 }
5029}
5030
5031TEST_F(URLRequestTestHTTP, CancelTest3) {
5032 ASSERT_TRUE(test_server_.Start());
5033
5034 TestDelegate d;
5035 {
[email protected]f7022f32014-08-21 16:32:195036 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365037 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445038
5039 d.set_cancel_in_received_data(true);
5040
[email protected]f7022f32014-08-21 16:32:195041 r->Start();
5042 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445043
[email protected]255620da2013-08-19 13:14:295044 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445045
5046 EXPECT_EQ(1, d.response_started_count());
5047 // There is no guarantee about how much data was received
5048 // before the cancel was issued. It could have been 0 bytes,
5049 // or it could have been all the bytes.
5050 // EXPECT_EQ(0, d.bytes_received());
5051 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195052 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445053 }
5054}
5055
5056TEST_F(URLRequestTestHTTP, CancelTest4) {
5057 ASSERT_TRUE(test_server_.Start());
5058
5059 TestDelegate d;
5060 {
[email protected]f7022f32014-08-21 16:32:195061 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365062 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445063
[email protected]f7022f32014-08-21 16:32:195064 r->Start();
5065 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445066
5067 // The request will be implicitly canceled when it is destroyed. The
5068 // test delegate must not post a quit message when this happens because
5069 // this test doesn't actually have a message loop. The quit message would
5070 // get put on this thread's message queue and the next test would exit
5071 // early, causing problems.
5072 d.set_quit_on_complete(false);
5073 }
5074 // expect things to just cleanup properly.
5075
5076 // we won't actually get a received reponse here because we've never run the
5077 // message loop
5078 EXPECT_FALSE(d.received_data_before_response());
5079 EXPECT_EQ(0, d.bytes_received());
5080}
5081
5082TEST_F(URLRequestTestHTTP, CancelTest5) {
5083 ASSERT_TRUE(test_server_.Start());
5084
5085 // populate cache
5086 {
5087 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195088 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365089 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195090 r->Start();
[email protected]255620da2013-08-19 13:14:295091 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195092 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445093 }
5094
5095 // cancel read from cache (see bug 990242)
5096 {
5097 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195098 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365099 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195100 r->Start();
5101 r->Cancel();
[email protected]255620da2013-08-19 13:14:295102 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445103
[email protected]f7022f32014-08-21 16:32:195104 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445105 EXPECT_EQ(1, d.response_started_count());
5106 EXPECT_EQ(0, d.bytes_received());
5107 EXPECT_FALSE(d.received_data_before_response());
5108 }
5109}
5110
5111TEST_F(URLRequestTestHTTP, PostTest) {
5112 ASSERT_TRUE(test_server_.Start());
5113 HTTPUploadDataOperationTest("POST");
5114}
5115
5116TEST_F(URLRequestTestHTTP, PutTest) {
5117 ASSERT_TRUE(test_server_.Start());
5118 HTTPUploadDataOperationTest("PUT");
5119}
5120
5121TEST_F(URLRequestTestHTTP, PostEmptyTest) {
5122 ASSERT_TRUE(test_server_.Start());
5123
5124 TestDelegate d;
5125 {
[email protected]f7022f32014-08-21 16:32:195126 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365127 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195128 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445129
[email protected]f7022f32014-08-21 16:32:195130 r->Start();
5131 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445132
[email protected]255620da2013-08-19 13:14:295133 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445134
[email protected]329b68b2012-11-14 17:54:275135 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195136 << "request failed: " << r->status().status()
5137 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445138
5139 EXPECT_FALSE(d.received_data_before_response());
5140 EXPECT_TRUE(d.data_received().empty());
5141 }
5142}
5143
5144TEST_F(URLRequestTestHTTP, PostFileTest) {
5145 ASSERT_TRUE(test_server_.Start());
5146
5147 TestDelegate d;
5148 {
[email protected]f7022f32014-08-21 16:32:195149 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365150 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195151 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445152
[email protected]6cdfd7f2013-02-08 20:40:155153 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445154 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025155 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445156
[email protected]f288ef02012-12-15 20:28:285157 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445158
[email protected]6cdfd7f2013-02-08 20:40:155159 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445160 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475161 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445162 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:365163 element_readers.push_back(
skyostil4891b25b2015-06-11 11:43:455164 new UploadFileElementReader(base::ThreadTaskRunnerHandle::Get().get(),
5165 path, 0, kuint64max, base::Time()));
mmenkecbc2b712014-10-09 20:29:075166 r->set_upload(make_scoped_ptr<UploadDataStream>(
5167 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:445168
[email protected]f7022f32014-08-21 16:32:195169 r->Start();
5170 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445171
[email protected]255620da2013-08-19 13:14:295172 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445173
pkasting6b68a162014-12-01 22:10:295174 int64 size64 = 0;
5175 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5176 ASSERT_LE(size64, std::numeric_limits<int>::max());
5177 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175178 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445179
[email protected]7600d0b2013-12-08 21:43:305180 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445181
[email protected]329b68b2012-11-14 17:54:275182 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195183 << "request failed: " << r->status().status()
5184 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445185
5186 EXPECT_FALSE(d.received_data_before_response());
5187
[email protected]329b68b2012-11-14 17:54:275188 EXPECT_EQ(size, d.bytes_received());
5189 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445190 }
5191}
5192
[email protected]999dd8c2013-11-12 06:45:545193TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
5194 ASSERT_TRUE(test_server_.Start());
5195
5196 TestDelegate d;
5197 {
[email protected]f7022f32014-08-21 16:32:195198 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365199 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195200 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545201
5202 ScopedVector<UploadElementReader> element_readers;
5203
5204 element_readers.push_back(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455205 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545206 base::FilePath(FILE_PATH_LITERAL(
5207 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
skyostil4891b25b2015-06-11 11:43:455208 0, kuint64max, base::Time()));
mmenkecbc2b712014-10-09 20:29:075209 r->set_upload(make_scoped_ptr<UploadDataStream>(
5210 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]999dd8c2013-11-12 06:45:545211
[email protected]f7022f32014-08-21 16:32:195212 r->Start();
5213 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545214
5215 base::RunLoop().Run();
5216
[email protected]999dd8c2013-11-12 06:45:545217 EXPECT_TRUE(d.request_failed());
5218 EXPECT_FALSE(d.received_data_before_response());
5219 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195220 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5221 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545222 }
5223}
5224
[email protected]316c1e5e2012-09-12 15:17:445225TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5226 ASSERT_TRUE(test_server_.Start());
5227
5228 TestDelegate d;
5229 {
[email protected]f7022f32014-08-21 16:32:195230 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365231 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195232 r->EnableChunkedUpload();
5233 r->set_method("POST");
5234 AddChunksToUpload(r.get());
5235 r->Start();
5236 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445237
[email protected]255620da2013-08-19 13:14:295238 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445239
[email protected]f7022f32014-08-21 16:32:195240 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445241 }
5242}
5243
[email protected]329b68b2012-11-14 17:54:275244TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5245 ASSERT_TRUE(test_server_.Start());
5246
5247 TestDelegate d;
5248 {
[email protected]f7022f32014-08-21 16:32:195249 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365250 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195251 r->EnableChunkedUpload();
5252 r->set_method("POST");
5253 r->Start();
5254 EXPECT_TRUE(r->is_pending());
5255 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295256 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275257
[email protected]f7022f32014-08-21 16:32:195258 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275259 }
5260}
5261
[email protected]316c1e5e2012-09-12 15:17:445262TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5263 ASSERT_TRUE(test_server_.Start());
5264
5265 TestDelegate d;
5266 {
[email protected]f7022f32014-08-21 16:32:195267 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365268 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195269 r->EnableChunkedUpload();
5270 r->set_method("POST");
5271 r->Start();
5272 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445273
[email protected]255620da2013-08-19 13:14:295274 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195275 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295276 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445277
[email protected]f7022f32014-08-21 16:32:195278 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445279 }
5280}
5281
5282TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5283 ASSERT_TRUE(test_server_.Start());
5284
5285 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195286 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365287 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195288 req->Start();
[email protected]255620da2013-08-19 13:14:295289 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445290
[email protected]f7022f32014-08-21 16:32:195291 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445292
5293 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195294 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445295
5296 std::string header;
5297 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5298 EXPECT_EQ("private", header);
5299
5300 header.clear();
5301 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5302 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5303
5304 // The response has two "X-Multiple-Entries" headers.
5305 // This verfies our output has them concatenated together.
5306 header.clear();
5307 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5308 EXPECT_EQ("a, b", header);
5309}
5310
[email protected]242d8562012-10-30 21:20:465311TEST_F(URLRequestTestHTTP, ProcessSTS) {
estarka5da76702015-04-09 04:00:165312 SpawnedTestServer::SSLOptions ssl_options(
5313 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475314 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5315 ssl_options,
5316 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465317 ASSERT_TRUE(https_test_server.Start());
5318
estarka5da76702015-04-09 04:00:165319 std::string test_server_hostname = https_test_server.GetURL("").host();
5320
[email protected]242d8562012-10-30 21:20:465321 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195322 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365323 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5324 &d));
[email protected]f7022f32014-08-21 16:32:195325 request->Start();
[email protected]255620da2013-08-19 13:14:295326 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465327
5328 TransportSecurityState* security_state =
5329 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465330 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165331 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5332 &domain_state));
[email protected]242d8562012-10-30 21:20:465333 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265334 domain_state.sts.upgrade_mode);
5335 EXPECT_TRUE(domain_state.sts.include_subdomains);
5336 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275337#if defined(OS_ANDROID)
5338 // Android's CertVerifyProc does not (yet) handle pins.
5339#else
5340 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5341#endif
5342}
5343
estarka5da76702015-04-09 04:00:165344TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
mmenke9f2ec60c2015-06-01 20:59:475345 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5346 SpawnedTestServer::SSLOptions(),
5347 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165348 ASSERT_TRUE(https_test_server.Start());
5349 // Make sure this test fails if the test server is changed to not
5350 // listen on an IP by default.
5351 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5352 std::string test_server_hostname = https_test_server.GetURL("").host();
5353
5354 TestDelegate d;
5355 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5356 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5357 &d));
5358 request->Start();
5359 base::RunLoop().Run();
5360
5361 TransportSecurityState* security_state =
5362 default_context_.transport_security_state();
5363 TransportSecurityState::DomainState domain_state;
5364 EXPECT_FALSE(security_state->GetDynamicDomainState(test_server_hostname,
5365 &domain_state));
5366}
5367
[email protected]37fd55fb2013-06-29 13:13:275368// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5369// reject HPKP headers, and a test setting only HPKP headers will fail (no
5370// DomainState present because header rejected).
5371#if defined(OS_ANDROID)
5372#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5373#else
5374#define MAYBE_ProcessPKP ProcessPKP
5375#endif
5376
5377// Tests that enabling HPKP on a domain does not affect the HSTS
5378// validity/expiration.
5379TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estarka5da76702015-04-09 04:00:165380 SpawnedTestServer::SSLOptions ssl_options(
5381 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475382 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5383 ssl_options,
5384 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275385 ASSERT_TRUE(https_test_server.Start());
5386
estarka5da76702015-04-09 04:00:165387 std::string test_server_hostname = https_test_server.GetURL("").host();
5388
[email protected]37fd55fb2013-06-29 13:13:275389 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195390 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365391 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5392 &d));
[email protected]f7022f32014-08-21 16:32:195393 request->Start();
[email protected]255620da2013-08-19 13:14:295394 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275395
5396 TransportSecurityState* security_state =
5397 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275398 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165399 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5400 &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275401 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
[email protected]9e6968d2014-05-07 21:46:265402 domain_state.sts.upgrade_mode);
5403 EXPECT_FALSE(domain_state.sts.include_subdomains);
5404 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275405 EXPECT_TRUE(domain_state.HasPublicKeyPins());
[email protected]9e6968d2014-05-07 21:46:265406 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]242d8562012-10-30 21:20:465407}
5408
estarka5da76702015-04-09 04:00:165409TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
mmenke9f2ec60c2015-06-01 20:59:475410 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5411 SpawnedTestServer::SSLOptions(),
5412 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165413 ASSERT_TRUE(https_test_server.Start());
5414 // Make sure this test fails if the test server is changed to not
5415 // listen on an IP by default.
5416 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5417 std::string test_server_hostname = https_test_server.GetURL("").host();
5418
5419 TestDelegate d;
5420 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5421 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5422 &d));
5423 request->Start();
5424 base::RunLoop().Run();
5425
5426 TransportSecurityState* security_state =
5427 default_context_.transport_security_state();
5428 TransportSecurityState::DomainState domain_state;
5429 EXPECT_FALSE(security_state->GetDynamicDomainState(test_server_hostname,
5430 &domain_state));
5431}
5432
[email protected]242d8562012-10-30 21:20:465433TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
estarka5da76702015-04-09 04:00:165434 SpawnedTestServer::SSLOptions ssl_options(
5435 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475436 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5437 ssl_options,
5438 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465439 ASSERT_TRUE(https_test_server.Start());
5440
estarka5da76702015-04-09 04:00:165441 std::string test_server_hostname = https_test_server.GetURL("").host();
5442
[email protected]242d8562012-10-30 21:20:465443 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195444 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]242d8562012-10-30 21:20:465445 https_test_server.GetURL("files/hsts-multiple-headers.html"),
davidben151423e2015-03-23 18:48:365446 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195447 request->Start();
[email protected]255620da2013-08-19 13:14:295448 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465449
5450 // We should have set parameters from the first header, not the second.
5451 TransportSecurityState* security_state =
5452 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465453 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165454 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5455 &domain_state));
[email protected]242d8562012-10-30 21:20:465456 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265457 domain_state.sts.upgrade_mode);
5458 EXPECT_FALSE(domain_state.sts.include_subdomains);
5459 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]242d8562012-10-30 21:20:465460}
5461
[email protected]9f972ec2013-04-10 20:24:365462TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
estarka5da76702015-04-09 04:00:165463 SpawnedTestServer::SSLOptions ssl_options(
5464 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475465 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5466 ssl_options,
5467 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:365468 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]9f972ec2013-04-10 20:24:365472 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195473 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]9f972ec2013-04-10 20:24:365474 https_test_server.GetURL("files/hsts-and-hpkp-headers.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]9f972ec2013-04-10 20:24:365478
5479 // We should have set parameters from the first header, not the second.
5480 TransportSecurityState* security_state =
5481 default_context_.transport_security_state();
[email protected]9f972ec2013-04-10 20:24:365482 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165483 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5484 &domain_state));
[email protected]9f972ec2013-04-10 20:24:365485 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265486 domain_state.sts.upgrade_mode);
[email protected]9f972ec2013-04-10 20:24:365487#if defined(OS_ANDROID)
5488 // Android's CertVerifyProc does not (yet) handle pins.
5489#else
5490 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5491#endif
[email protected]9e6968d2014-05-07 21:46:265492 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]9f972ec2013-04-10 20:24:365493
[email protected]a165f092013-06-12 16:10:055494 // Even though there is an HSTS header asserting includeSubdomains, it is
5495 // the *second* such header, and we MUST process only the first.
[email protected]9e6968d2014-05-07 21:46:265496 EXPECT_FALSE(domain_state.sts.include_subdomains);
[email protected]a165f092013-06-12 16:10:055497 // includeSubdomains does not occur in the test HPKP header.
[email protected]9e6968d2014-05-07 21:46:265498 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365499}
5500
[email protected]37fd55fb2013-06-29 13:13:275501// Tests that when multiple HPKP headers are present, asserting different
5502// policies, that only the first such policy is processed.
5503TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
estarka5da76702015-04-09 04:00:165504 SpawnedTestServer::SSLOptions ssl_options(
5505 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475506 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5507 ssl_options,
5508 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275509 ASSERT_TRUE(https_test_server.Start());
5510
estarka5da76702015-04-09 04:00:165511 std::string test_server_hostname = https_test_server.GetURL("").host();
5512
[email protected]37fd55fb2013-06-29 13:13:275513 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195514 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]37fd55fb2013-06-29 13:13:275515 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:365516 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195517 request->Start();
[email protected]255620da2013-08-19 13:14:295518 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275519
5520 TransportSecurityState* security_state =
5521 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275522 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165523 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5524 &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275525 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265526 domain_state.sts.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:275527#if defined(OS_ANDROID)
5528 // Android's CertVerifyProc does not (yet) handle pins.
5529#else
5530 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5531#endif
[email protected]9e6968d2014-05-07 21:46:265532 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]37fd55fb2013-06-29 13:13:275533
[email protected]9e6968d2014-05-07 21:46:265534 EXPECT_TRUE(domain_state.sts.include_subdomains);
5535 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275536}
5537
[email protected]316c1e5e2012-09-12 15:17:445538TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5539 ASSERT_TRUE(test_server_.Start());
5540
5541 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195542 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5543 test_server_.GetURL("files/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:365544 DEFAULT_PRIORITY, &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
5548 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:195549 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:445550 EXPECT_EQ("text/html", mime_type);
5551
5552 std::string charset;
[email protected]f7022f32014-08-21 16:32:195553 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:445554 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:195555 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445556}
5557
[email protected]02494ec2014-05-07 15:05:295558TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:345559 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:345560 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:345561 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025562 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345563
5564 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505565 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345566}
5567
[email protected]02494ec2014-05-07 15:05:295568#if !defined(DISABLE_FILE_SUPPORT)
5569TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5570 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5571 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:455572 FileProtocolHandler file_protocol_handler(
5573 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:295574 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5575
5576 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505577 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:295578}
5579
[email protected]588614c22013-08-16 00:09:025580TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445581 ASSERT_TRUE(test_server_.Start());
5582
5583 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195584 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365585 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY,
5586 &d));
[email protected]f7022f32014-08-21 16:32:195587 req->Start();
[email protected]255620da2013-08-19 13:14:295588 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445589
[email protected]f7022f32014-08-21 16:32:195590 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5591 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445592}
[email protected]02494ec2014-05-07 15:05:295593#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:445594
[email protected]588614c22013-08-16 00:09:025595TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5596 ASSERT_TRUE(test_server_.Start());
5597
5598 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195599 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365600 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY,
5601 &d));
[email protected]f7022f32014-08-21 16:32:195602 req->Start();
[email protected]588614c22013-08-16 00:09:025603 base::MessageLoop::current()->Run();
5604
[email protected]f7022f32014-08-21 16:32:195605 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5606 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:025607}
5608
[email protected]316c1e5e2012-09-12 15:17:445609TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5610 ASSERT_TRUE(test_server_.Start());
5611
5612 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195613 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5614 test_server_.GetURL("files/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:365615 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195616 req->Start();
[email protected]255620da2013-08-19 13:14:295617 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445618
[email protected]f7022f32014-08-21 16:32:195619 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5620 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445621}
5622
[email protected]e50efea2014-03-24 18:41:005623// Make sure redirects are cached, despite not reading their bodies.
5624TEST_F(URLRequestTestHTTP, CacheRedirect) {
5625 ASSERT_TRUE(test_server_.Start());
5626 GURL redirect_url =
5627 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5628
5629 {
5630 TestDelegate d;
davidben151423e2015-03-23 18:48:365631 scoped_ptr<URLRequest> req(
5632 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195633 req->Start();
[email protected]e50efea2014-03-24 18:41:005634 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195635 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005636 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195637 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005638 }
5639
5640 {
5641 TestDelegate d;
5642 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:365643 scoped_ptr<URLRequest> req(
5644 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195645 req->Start();
[email protected]e50efea2014-03-24 18:41:005646 base::RunLoop().Run();
5647
5648 EXPECT_EQ(1, d.received_redirect_count());
5649 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195650 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005651
[email protected]f7022f32014-08-21 16:32:195652 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:005653 base::RunLoop().Run();
5654 EXPECT_EQ(1, d.received_redirect_count());
5655 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195656 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5657 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005658 }
5659}
5660
5661// Make sure a request isn't cached when a NetworkDelegate forces a redirect
5662// when the headers are read, since the body won't have been read.
5663TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5664 ASSERT_TRUE(test_server_.Start());
5665 // URL that is normally cached.
5666 GURL initial_url = test_server_.GetURL("cachetime");
5667
5668 {
5669 // Set up the TestNetworkDelegate tp force a redirect.
5670 GURL redirect_to_url = test_server_.GetURL("echo");
5671 default_network_delegate_.set_redirect_on_headers_received_url(
5672 redirect_to_url);
5673
5674 TestDelegate d;
davidben151423e2015-03-23 18:48:365675 scoped_ptr<URLRequest> req(
5676 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195677 req->Start();
[email protected]e50efea2014-03-24 18:41:005678 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195679 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005680 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195681 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:005682 }
5683
5684 {
5685 TestDelegate d;
davidben151423e2015-03-23 18:48:365686 scoped_ptr<URLRequest> req(
5687 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195688 req->Start();
[email protected]e50efea2014-03-24 18:41:005689 base::RunLoop().Run();
5690
[email protected]f7022f32014-08-21 16:32:195691 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5692 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005693 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195694 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:005695 }
5696}
5697
[email protected]5f714132014-03-26 10:41:165698// Tests that redirection to an unsafe URL is allowed when it has been marked as
5699// safe.
5700TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5701 ASSERT_TRUE(test_server_.Start());
5702
5703 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5704 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5705 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5706
5707 TestDelegate d;
5708 {
[email protected]f7022f32014-08-21 16:32:195709 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365710 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165711
[email protected]f7022f32014-08-21 16:32:195712 r->Start();
[email protected]5f714132014-03-26 10:41:165713 base::RunLoop().Run();
5714
[email protected]f7022f32014-08-21 16:32:195715 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:165716
[email protected]f7022f32014-08-21 16:32:195717 EXPECT_EQ(2U, r->url_chain().size());
5718 EXPECT_EQ(OK, r->status().error());
5719 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:165720 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5721 }
5722}
5723
5724// Tests that a redirect to a different unsafe URL is blocked, even after adding
5725// some other URL to the whitelist.
5726TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5727 ASSERT_TRUE(test_server_.Start());
5728
5729 GURL unsafe_url("data:text/html,something");
5730 GURL different_unsafe_url("data:text/html,something-else");
5731 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5732 default_network_delegate_.set_allowed_unsafe_redirect_url(
5733 different_unsafe_url);
5734
5735 TestDelegate d;
5736 {
[email protected]f7022f32014-08-21 16:32:195737 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365738 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165739
[email protected]f7022f32014-08-21 16:32:195740 r->Start();
[email protected]5f714132014-03-26 10:41:165741 base::RunLoop().Run();
5742
[email protected]f7022f32014-08-21 16:32:195743 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5744 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:165745 }
5746}
5747
[email protected]5f714132014-03-26 10:41:165748// Redirects from an URL with fragment to an unsafe URL with fragment should
5749// be allowed, and the reference fragment of the target URL should be preserved.
5750TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5751 ASSERT_TRUE(test_server_.Start());
5752
5753 GURL original_url(test_server_.GetURL("original#fragment1"));
5754 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5755 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5756
5757 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5758 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5759
5760 TestDelegate d;
5761 {
davidben151423e2015-03-23 18:48:365762 scoped_ptr<URLRequest> r(
5763 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165764
[email protected]f7022f32014-08-21 16:32:195765 r->Start();
[email protected]5f714132014-03-26 10:41:165766 base::RunLoop().Run();
5767
[email protected]f7022f32014-08-21 16:32:195768 EXPECT_EQ(2U, r->url_chain().size());
5769 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5770 EXPECT_EQ(OK, r->status().error());
5771 EXPECT_EQ(original_url, r->original_url());
5772 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:165773 }
5774}
5775
5776// When a delegate has specified a safe redirect URL, but it does not match the
5777// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:145778TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:165779 ASSERT_TRUE(test_server_.Start());
5780
5781 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5782 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5783 GURL redirect_url(test_server_.GetURL("target"));
5784 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5785
5786 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5787 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5788
5789 TestDelegate d;
5790 {
davidben151423e2015-03-23 18:48:365791 scoped_ptr<URLRequest> r(
5792 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165793
[email protected]f7022f32014-08-21 16:32:195794 r->Start();
[email protected]5f714132014-03-26 10:41:165795 base::RunLoop().Run();
5796
[email protected]f7022f32014-08-21 16:32:195797 EXPECT_EQ(2U, r->url_chain().size());
5798 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5799 EXPECT_EQ(OK, r->status().error());
5800 EXPECT_EQ(original_url, r->original_url());
5801 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:165802 }
5803}
5804
[email protected]f878230e2014-04-03 15:36:145805// When a delegate has specified a safe redirect URL, assume that the redirect
5806// URL should not be changed. In particular, the reference fragment should not
5807// be modified.
5808TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5809 ASSERT_TRUE(test_server_.Start());
5810
5811 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5812 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5813
5814 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5815 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5816
5817 TestDelegate d;
5818 {
davidben151423e2015-03-23 18:48:365819 scoped_ptr<URLRequest> r(
5820 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145821
[email protected]f7022f32014-08-21 16:32:195822 r->Start();
[email protected]f878230e2014-04-03 15:36:145823 base::RunLoop().Run();
5824
[email protected]f7022f32014-08-21 16:32:195825 EXPECT_EQ(2U, r->url_chain().size());
5826 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5827 EXPECT_EQ(OK, r->status().error());
5828 EXPECT_EQ(original_url, r->original_url());
5829 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145830 }
5831}
5832
5833// When a URLRequestRedirectJob is created, the redirection must be followed and
5834// the reference fragment of the target URL must not be modified.
5835TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5836 ASSERT_TRUE(test_server_.Start());
5837
5838 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5839 GURL redirect_url(test_server_.GetURL("echo"));
5840
5841 TestDelegate d;
davidben151423e2015-03-23 18:48:365842 scoped_ptr<URLRequest> r(
5843 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145844
5845 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:195846 r.get(), &default_network_delegate_, redirect_url,
[email protected]f878230e2014-04-03 15:36:145847 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5848 AddTestInterceptor()->set_main_intercept_job(job);
5849
[email protected]f7022f32014-08-21 16:32:195850 r->Start();
[email protected]f878230e2014-04-03 15:36:145851 base::RunLoop().Run();
5852
[email protected]f7022f32014-08-21 16:32:195853 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5854 EXPECT_EQ(OK, r->status().error());
5855 EXPECT_EQ(original_url, r->original_url());
5856 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145857}
5858
[email protected]316c1e5e2012-09-12 15:17:445859TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5860 ASSERT_TRUE(test_server_.Start());
5861
5862 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195863 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365864 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195865 req->SetReferrer("http://user:[email protected]/");
5866 req->Start();
[email protected]255620da2013-08-19 13:14:295867 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445868
5869 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5870}
5871
[email protected]99ecf6e2013-04-10 22:46:135872TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5873 ASSERT_TRUE(test_server_.Start());
5874
5875 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195876 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365877 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195878 req->SetReferrer("http://foo.com/test#fragment");
5879 req->Start();
[email protected]255620da2013-08-19 13:14:295880 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135881
5882 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5883}
5884
5885TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5886 ASSERT_TRUE(test_server_.Start());
5887
5888 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195889 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365890 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195891 req->SetReferrer("http://foo.com/test#fragment");
5892 req->SetReferrer("");
5893 req->Start();
[email protected]255620da2013-08-19 13:14:295894 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135895
5896 EXPECT_EQ(std::string("None"), d.data_received());
5897}
5898
[email protected]1826a402014-01-08 15:40:485899// Defer network start and then resume, checking that the request was a success
5900// and bytes were received.
5901TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5902 ASSERT_TRUE(test_server_.Start());
5903
5904 TestDelegate d;
5905 {
5906 d.set_quit_on_network_start(true);
5907 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365908 scoped_ptr<URLRequest> req(
5909 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485910
[email protected]f7022f32014-08-21 16:32:195911 req->Start();
[email protected]1826a402014-01-08 15:40:485912 base::RunLoop().Run();
5913
5914 EXPECT_EQ(1, d.received_before_network_start_count());
5915 EXPECT_EQ(0, d.response_started_count());
5916
[email protected]f7022f32014-08-21 16:32:195917 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485918 base::RunLoop().Run();
5919
5920 EXPECT_EQ(1, d.response_started_count());
5921 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195922 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485923 }
5924}
5925
5926// Check that OnBeforeNetworkStart is only called once even if there is a
5927// redirect.
5928TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5929 ASSERT_TRUE(test_server_.Start());
5930
5931 TestDelegate d;
5932 {
5933 d.set_quit_on_redirect(true);
5934 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:195935 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365936 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485937
[email protected]f7022f32014-08-21 16:32:195938 req->Start();
[email protected]1826a402014-01-08 15:40:485939 base::RunLoop().Run();
5940
5941 EXPECT_EQ(1, d.received_before_network_start_count());
5942 EXPECT_EQ(0, d.response_started_count());
5943 EXPECT_EQ(0, d.received_redirect_count());
5944
[email protected]f7022f32014-08-21 16:32:195945 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485946 base::RunLoop().Run();
5947
5948 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195949 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:485950 base::RunLoop().Run();
5951
5952 // Check that the redirect's new network transaction does not get propagated
5953 // to a second OnBeforeNetworkStart() notification.
5954 EXPECT_EQ(1, d.received_before_network_start_count());
5955
5956 EXPECT_EQ(1, d.response_started_count());
5957 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195958 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485959 }
5960}
5961
5962// Cancel the request after learning that the request would use the network.
5963TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5964 ASSERT_TRUE(test_server_.Start());
5965
5966 TestDelegate d;
5967 {
5968 d.set_quit_on_network_start(true);
5969 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365970 scoped_ptr<URLRequest> req(
5971 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485972
[email protected]f7022f32014-08-21 16:32:195973 req->Start();
[email protected]1826a402014-01-08 15:40:485974 base::RunLoop().Run();
5975
5976 EXPECT_EQ(1, d.received_before_network_start_count());
5977 EXPECT_EQ(0, d.response_started_count());
5978
[email protected]f7022f32014-08-21 16:32:195979 req->Cancel();
[email protected]1826a402014-01-08 15:40:485980 base::RunLoop().Run();
5981
5982 EXPECT_EQ(1, d.response_started_count());
5983 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195984 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:485985 }
5986}
5987
[email protected]316c1e5e2012-09-12 15:17:445988TEST_F(URLRequestTestHTTP, CancelRedirect) {
5989 ASSERT_TRUE(test_server_.Start());
5990
5991 TestDelegate d;
5992 {
5993 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:195994 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365995 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195996 req->Start();
[email protected]255620da2013-08-19 13:14:295997 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445998
5999 EXPECT_EQ(1, d.response_started_count());
6000 EXPECT_EQ(0, d.bytes_received());
6001 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196002 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446003 }
6004}
6005
6006TEST_F(URLRequestTestHTTP, DeferredRedirect) {
6007 ASSERT_TRUE(test_server_.Start());
6008
6009 TestDelegate d;
6010 {
6011 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:046012 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366013 scoped_ptr<URLRequest> req(
6014 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046015
[email protected]f7022f32014-08-21 16:32:196016 req->Start();
[email protected]255620da2013-08-19 13:14:296017 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446018
6019 EXPECT_EQ(1, d.received_redirect_count());
6020
[email protected]f7022f32014-08-21 16:32:196021 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296022 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446023
6024 EXPECT_EQ(1, d.response_started_count());
6025 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196026 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446027
[email protected]6cdfd7f2013-02-08 20:40:156028 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446029 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476030 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446031 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6032
6033 std::string contents;
[email protected]82f84b92013-08-30 18:23:506034 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446035 EXPECT_EQ(contents, d.data_received());
6036 }
6037}
6038
[email protected]79e1fd62013-06-20 06:50:046039TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
6040 ASSERT_TRUE(test_server_.Start());
6041
6042 TestDelegate d;
6043 {
6044 d.set_quit_on_redirect(true);
6045 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366046 scoped_ptr<URLRequest> req(
6047 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046048
6049 EXPECT_FALSE(d.have_full_request_headers());
6050
[email protected]f7022f32014-08-21 16:32:196051 req->Start();
[email protected]255620da2013-08-19 13:14:296052 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046053
6054 EXPECT_EQ(1, d.received_redirect_count());
6055 EXPECT_TRUE(d.have_full_request_headers());
6056 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6057 d.ClearFullRequestHeaders();
6058
[email protected]f7022f32014-08-21 16:32:196059 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296060 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046061
6062 GURL target_url(test_server_.GetURL("files/with-headers.html"));
6063 EXPECT_EQ(1, d.response_started_count());
6064 EXPECT_TRUE(d.have_full_request_headers());
6065 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6066 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196067 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046068
6069 base::FilePath path;
6070 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476071 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046072 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6073
6074 std::string contents;
[email protected]82f84b92013-08-30 18:23:506075 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046076 EXPECT_EQ(contents, d.data_received());
6077 }
6078}
6079
[email protected]316c1e5e2012-09-12 15:17:446080TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
6081 ASSERT_TRUE(test_server_.Start());
6082
6083 TestDelegate d;
6084 {
6085 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196086 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366087 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196088 req->Start();
[email protected]255620da2013-08-19 13:14:296089 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446090
6091 EXPECT_EQ(1, d.received_redirect_count());
6092
[email protected]f7022f32014-08-21 16:32:196093 req->Cancel();
[email protected]255620da2013-08-19 13:14:296094 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446095
6096 EXPECT_EQ(1, d.response_started_count());
6097 EXPECT_EQ(0, d.bytes_received());
6098 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196099 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446100 }
6101}
6102
6103TEST_F(URLRequestTestHTTP, VaryHeader) {
6104 ASSERT_TRUE(test_server_.Start());
6105
[email protected]3b23a222013-05-15 21:33:256106 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446107 {
6108 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196109 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366110 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446111 HttpRequestHeaders headers;
6112 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196113 req->SetExtraRequestHeaders(headers);
6114 req->Start();
[email protected]255620da2013-08-19 13:14:296115 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256116
6117 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196118 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256119 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446120 }
6121
[email protected]3b23a222013-05-15 21:33:256122 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446123 {
6124 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196125 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366126 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446127 HttpRequestHeaders headers;
6128 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196129 req->SetExtraRequestHeaders(headers);
6130 req->Start();
[email protected]255620da2013-08-19 13:14:296131 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446132
[email protected]f7022f32014-08-21 16:32:196133 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256134
6135 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196136 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256137 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446138 }
6139
[email protected]3b23a222013-05-15 21:33:256140 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446141 {
6142 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196143 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366144 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446145 HttpRequestHeaders headers;
6146 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196147 req->SetExtraRequestHeaders(headers);
6148 req->Start();
[email protected]255620da2013-08-19 13:14:296149 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446150
[email protected]f7022f32014-08-21 16:32:196151 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256152
6153 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196154 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256155 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446156 }
6157}
6158
6159TEST_F(URLRequestTestHTTP, BasicAuth) {
6160 ASSERT_TRUE(test_server_.Start());
6161
6162 // populate the cache
6163 {
6164 TestDelegate d;
6165 d.set_credentials(AuthCredentials(kUser, kSecret));
6166
[email protected]f7022f32014-08-21 16:32:196167 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366168 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196169 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446170
[email protected]255620da2013-08-19 13:14:296171 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446172
6173 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6174 }
6175
6176 // repeat request with end-to-end validation. since auth-basic results in a
6177 // cachable page, we expect this test to result in a 304. in which case, the
6178 // response should be fetched from the cache.
6179 {
6180 TestDelegate d;
6181 d.set_credentials(AuthCredentials(kUser, kSecret));
6182
[email protected]f7022f32014-08-21 16:32:196183 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366184 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196185 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6186 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446187
[email protected]255620da2013-08-19 13:14:296188 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446189
6190 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6191
6192 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196193 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446194 }
6195}
6196
6197// Check that Set-Cookie headers in 401 responses are respected.
6198// http://crbug.com/6450
6199TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6200 ASSERT_TRUE(test_server_.Start());
6201
6202 GURL url_requiring_auth =
6203 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6204
6205 // Request a page that will give a 401 containing a Set-Cookie header.
6206 // Verify that when the transaction is restarted, it includes the new cookie.
6207 {
[email protected]ceefd7fd2012-11-29 00:36:246208 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446209 TestURLRequestContext context(true);
6210 context.set_network_delegate(&network_delegate);
6211 context.Init();
6212
6213 TestDelegate d;
6214 d.set_credentials(AuthCredentials(kUser, kSecret));
6215
davidben151423e2015-03-23 18:48:366216 scoped_ptr<URLRequest> r(
6217 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196218 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446219
[email protected]255620da2013-08-19 13:14:296220 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446221
6222 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6223
6224 // Make sure we sent the cookie in the restarted transaction.
6225 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6226 != std::string::npos);
6227 }
6228
6229 // Same test as above, except this time the restart is initiated earlier
6230 // (without user intervention since identity is embedded in the URL).
6231 {
[email protected]ceefd7fd2012-11-29 00:36:246232 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446233 TestURLRequestContext context(true);
6234 context.set_network_delegate(&network_delegate);
6235 context.Init();
6236
6237 TestDelegate d;
6238
6239 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186240 replacements.SetUsernameStr("user2");
6241 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446242 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6243
davidben151423e2015-03-23 18:48:366244 scoped_ptr<URLRequest> r(
6245 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196246 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446247
[email protected]255620da2013-08-19 13:14:296248 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446249
6250 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6251
6252 // Make sure we sent the cookie in the restarted transaction.
6253 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6254 != std::string::npos);
6255 }
6256}
6257
[email protected]58e32bb2013-01-21 18:23:256258// Tests that load timing works as expected with auth and the cache.
6259TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6260 ASSERT_TRUE(test_server_.Start());
6261
6262 // populate the cache
6263 {
6264 TestDelegate d;
6265 d.set_credentials(AuthCredentials(kUser, kSecret));
6266
[email protected]f7022f32014-08-21 16:32:196267 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366268 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196269 r->Start();
[email protected]58e32bb2013-01-21 18:23:256270
[email protected]255620da2013-08-19 13:14:296271 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256272
6273 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6274
6275 LoadTimingInfo load_timing_info_before_auth;
6276 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6277 &load_timing_info_before_auth));
6278 TestLoadTimingNotReused(load_timing_info_before_auth,
6279 CONNECT_TIMING_HAS_DNS_TIMES);
6280
6281 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196282 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256283 // The test server does not support keep alive sockets, so the second
6284 // request with auth should use a new socket.
6285 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6286 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6287 load_timing_info.socket_log_id);
6288 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6289 load_timing_info.connect_timing.connect_start);
6290 }
6291
[email protected]3b23a222013-05-15 21:33:256292 // Repeat request with end-to-end validation. Since auth-basic results in a
6293 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256294 // response should be fetched from the cache.
6295 {
6296 TestDelegate d;
6297 d.set_credentials(AuthCredentials(kUser, kSecret));
6298
[email protected]f7022f32014-08-21 16:32:196299 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366300 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196301 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6302 r->Start();
[email protected]58e32bb2013-01-21 18:23:256303
[email protected]255620da2013-08-19 13:14:296304 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256305
6306 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6307
6308 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196309 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256310
[email protected]3b23a222013-05-15 21:33:256311 // Since there was a request that went over the wire, the load timing
6312 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256313 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196314 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256315 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256316 }
6317}
6318
[email protected]316c1e5e2012-09-12 15:17:446319// In this test, we do a POST which the server will 302 redirect.
6320// The subsequent transaction should use GET, and should not send the
6321// Content-Type header.
6322// http://code.google.com/p/chromium/issues/detail?id=843
6323TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6324 ASSERT_TRUE(test_server_.Start());
6325
6326 const char kData[] = "hello world";
6327
6328 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196329 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366330 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196331 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076332 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446333
6334 // Set headers (some of which are specific to the POST).
6335 HttpRequestHeaders headers;
6336 headers.AddHeadersFromString(
6337 "Content-Type: multipart/form-data; "
6338 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6339 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6340 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6341 "Accept-Language: en-US,en\r\n"
6342 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6343 "Content-Length: 11\r\n"
6344 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196345 req->SetExtraRequestHeaders(headers);
6346 req->Start();
[email protected]255620da2013-08-19 13:14:296347 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446348
6349 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196350 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446351 EXPECT_EQ("text/html", mime_type);
6352
6353 const std::string& data = d.data_received();
6354
6355 // Check that the post-specific headers were stripped:
6356 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6357 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6358 EXPECT_FALSE(ContainsString(data, "Origin:"));
6359
6360 // These extra request headers should not have been stripped.
6361 EXPECT_TRUE(ContainsString(data, "Accept:"));
6362 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6363 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6364}
6365
jww5fe460ff2015-03-28 00:22:516366// The following tests check that we handle mutating the request for HTTP
6367// redirects as expected.
6368// See https://crbug.com/56373, https://crbug.com/102130, and
6369// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:446370
6371TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6372 ASSERT_TRUE(test_server_.Start());
6373
6374 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:516375 const GURL https_redirect_url =
6376 test_server_.GetURL("files/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:446377
6378 HTTPRedirectMethodTest(url, "POST", "GET", true);
6379 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6380 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516381
6382 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6383 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6384 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6385 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6386 std::string());
[email protected]316c1e5e2012-09-12 15:17:446387}
6388
6389TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6390 ASSERT_TRUE(test_server_.Start());
6391
6392 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:516393 const GURL https_redirect_url =
6394 test_server_.GetURL("files/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:446395
6396 HTTPRedirectMethodTest(url, "POST", "GET", true);
6397 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6398 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516399
6400 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6401 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6402 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6403 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6404 std::string());
[email protected]316c1e5e2012-09-12 15:17:446405}
6406
6407TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6408 ASSERT_TRUE(test_server_.Start());
6409
6410 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:516411 const GURL https_redirect_url =
6412 test_server_.GetURL("files/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:446413
6414 HTTPRedirectMethodTest(url, "POST", "GET", true);
6415 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6416 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516417
6418 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6419 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6420 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6421 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6422 std::string());
[email protected]316c1e5e2012-09-12 15:17:446423}
6424
6425TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6426 ASSERT_TRUE(test_server_.Start());
6427
6428 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:516429 const GURL https_redirect_url =
6430 test_server_.GetURL("files/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:446431
6432 HTTPRedirectMethodTest(url, "POST", "POST", true);
6433 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6434 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516435
6436 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6437 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6438 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6439 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:446440}
6441
[email protected]0a17aab32014-04-24 03:32:376442TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6443 ASSERT_TRUE(test_server_.Start());
6444
6445 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:516446 const GURL https_redirect_url =
6447 test_server_.GetURL("files/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:376448
6449 HTTPRedirectMethodTest(url, "POST", "POST", true);
6450 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6451 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516452
6453 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6454 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6455 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6456 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:376457}
6458
6459// Make sure that 308 responses without bodies are not treated as redirects.
6460// Certain legacy apis that pre-date the response code expect this behavior
6461// (Like Google Drive).
6462TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6463 ASSERT_TRUE(test_server_.Start());
6464
6465 TestDelegate d;
6466 const GURL url = test_server_.GetURL("files/308-without-location-header");
6467
davidben151423e2015-03-23 18:48:366468 scoped_ptr<URLRequest> request(
6469 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:376470
[email protected]f7022f32014-08-21 16:32:196471 request->Start();
[email protected]0a17aab32014-04-24 03:32:376472 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196473 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6474 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:376475 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196476 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:376477 EXPECT_EQ("This is not a redirect.", d.data_received());
6478}
6479
[email protected]f878230e2014-04-03 15:36:146480TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6481 ASSERT_TRUE(test_server_.Start());
6482
6483 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6484 GURL expected_url(test_server_.GetURL("echo#fragment"));
6485
6486 TestDelegate d;
6487 {
davidben151423e2015-03-23 18:48:366488 scoped_ptr<URLRequest> r(
6489 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146490
[email protected]f7022f32014-08-21 16:32:196491 r->Start();
[email protected]f878230e2014-04-03 15:36:146492 base::RunLoop().Run();
6493
[email protected]f7022f32014-08-21 16:32:196494 EXPECT_EQ(2U, r->url_chain().size());
6495 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6496 EXPECT_EQ(OK, r->status().error());
6497 EXPECT_EQ(original_url, r->original_url());
6498 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:146499 }
6500}
6501
[email protected]cba24642014-08-15 20:49:596502TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6503 ASSERT_TRUE(test_server_.Start());
6504
6505 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6506 GURL first_party_url("http://example.com");
6507
6508 TestDelegate d;
6509 {
davidben151423e2015-03-23 18:48:366510 scoped_ptr<URLRequest> r(
6511 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196512 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:596513
[email protected]f7022f32014-08-21 16:32:196514 r->Start();
[email protected]cba24642014-08-15 20:49:596515 base::RunLoop().Run();
6516
[email protected]f7022f32014-08-21 16:32:196517 EXPECT_EQ(2U, r->url_chain().size());
6518 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6519 EXPECT_EQ(OK, r->status().error());
6520 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596521 }
6522}
6523
6524TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6525 ASSERT_TRUE(test_server_.Start());
6526
6527 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6528 GURL original_first_party_url("http://example.com");
6529 GURL expected_first_party_url(test_server_.GetURL("echo"));
6530
6531 TestDelegate d;
6532 {
davidben151423e2015-03-23 18:48:366533 scoped_ptr<URLRequest> r(
6534 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196535 r->set_first_party_for_cookies(original_first_party_url);
6536 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:596537 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6538
[email protected]f7022f32014-08-21 16:32:196539 r->Start();
[email protected]cba24642014-08-15 20:49:596540 base::RunLoop().Run();
6541
[email protected]f7022f32014-08-21 16:32:196542 EXPECT_EQ(2U, r->url_chain().size());
6543 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6544 EXPECT_EQ(OK, r->status().error());
6545 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596546 }
6547}
6548
[email protected]316c1e5e2012-09-12 15:17:446549TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6550 ASSERT_TRUE(test_server_.Start());
6551
6552 const char kData[] = "hello world";
6553
6554 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196555 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366556 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196557 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076558 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446559 HttpRequestHeaders headers;
6560 headers.SetHeader(HttpRequestHeaders::kContentLength,
6561 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196562 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446563
6564 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196565 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096566 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446567 AddTestInterceptor()->set_main_intercept_job(job);
6568
[email protected]f7022f32014-08-21 16:32:196569 req->Start();
[email protected]255620da2013-08-19 13:14:296570 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196571 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:446572}
6573
6574TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6575 ASSERT_TRUE(test_server_.Start());
6576
6577 const char kData[] = "hello world";
6578
6579 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196580 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366581 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196582 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076583 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446584 HttpRequestHeaders headers;
6585 headers.SetHeader(HttpRequestHeaders::kContentLength,
6586 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196587 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446588
6589 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196590 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096591 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6592 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446593 AddTestInterceptor()->set_main_intercept_job(job);
6594
[email protected]f7022f32014-08-21 16:32:196595 req->Start();
[email protected]255620da2013-08-19 13:14:296596 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196597 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:446598 EXPECT_EQ(kData, d.data_received());
6599}
6600
6601// Check that default A-L header is sent.
6602TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6603 ASSERT_TRUE(test_server_.Start());
6604
[email protected]8790210c2013-12-02 05:29:536605 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:246606 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446607 TestURLRequestContext context(true);
6608 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:436609 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446610 context.Init();
6611
6612 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196613 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366614 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196615 req->Start();
[email protected]255620da2013-08-19 13:14:296616 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446617 EXPECT_EQ("en", d.data_received());
6618}
6619
6620// Check that an empty A-L header is not sent. http://crbug.com/77365.
6621TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6622 ASSERT_TRUE(test_server_.Start());
6623
[email protected]8790210c2013-12-02 05:29:536624 std::string empty_string; // Avoid most vexing parse on line below.
6625 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:246626 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446627 TestURLRequestContext context(true);
6628 context.set_network_delegate(&network_delegate);
6629 context.Init();
6630 // We override the language after initialization because empty entries
6631 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:436632 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446633
6634 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196635 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366636 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196637 req->Start();
[email protected]255620da2013-08-19 13:14:296638 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446639 EXPECT_EQ("None", d.data_received());
6640}
6641
6642// Check that if request overrides the A-L header, the default is not appended.
6643// See http://crbug.com/20894
6644TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6645 ASSERT_TRUE(test_server_.Start());
6646
6647 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196648 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366649 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446650 HttpRequestHeaders headers;
6651 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:196652 req->SetExtraRequestHeaders(headers);
6653 req->Start();
[email protected]255620da2013-08-19 13:14:296654 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446655 EXPECT_EQ(std::string("ru"), d.data_received());
6656}
6657
6658// Check that default A-E header is sent.
6659TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6660 ASSERT_TRUE(test_server_.Start());
6661
6662 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196663 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366664 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446665 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:196666 req->SetExtraRequestHeaders(headers);
6667 req->Start();
[email protected]255620da2013-08-19 13:14:296668 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446669 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6670}
6671
6672// Check that if request overrides the A-E header, the default is not appended.
6673// See http://crbug.com/47381
6674TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6675 ASSERT_TRUE(test_server_.Start());
6676
6677 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196678 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366679 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446680 HttpRequestHeaders headers;
6681 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:196682 req->SetExtraRequestHeaders(headers);
6683 req->Start();
[email protected]255620da2013-08-19 13:14:296684 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446685 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6686 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6687}
6688
[email protected]84f05432013-03-15 01:00:126689// Check that setting the A-C header sends the proper header.
6690TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:446691 ASSERT_TRUE(test_server_.Start());
6692
6693 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196694 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366695 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446696 HttpRequestHeaders headers;
6697 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:196698 req->SetExtraRequestHeaders(headers);
6699 req->Start();
[email protected]255620da2013-08-19 13:14:296700 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446701 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6702}
6703
6704// Check that default User-Agent header is sent.
6705TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6706 ASSERT_TRUE(test_server_.Start());
6707
6708 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196709 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366710 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196711 req->Start();
[email protected]255620da2013-08-19 13:14:296712 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196713 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:376714 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446715}
6716
6717// Check that if request overrides the User-Agent header,
6718// the default is not appended.
6719TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6720 ASSERT_TRUE(test_server_.Start());
6721
6722 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196723 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366724 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446725 HttpRequestHeaders headers;
6726 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:196727 req->SetExtraRequestHeaders(headers);
6728 req->Start();
[email protected]255620da2013-08-19 13:14:296729 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:356730 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446731}
6732
[email protected]ee4c30d2012-11-07 15:08:436733// Check that a NULL HttpUserAgentSettings causes the corresponding empty
6734// User-Agent header to be sent but does not send the Accept-Language and
6735// Accept-Charset headers.
6736TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6737 ASSERT_TRUE(test_server_.Start());
6738
[email protected]ceefd7fd2012-11-29 00:36:246739 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:436740 TestURLRequestContext context(true);
6741 context.set_network_delegate(&network_delegate);
6742 context.Init();
6743 // We override the HttpUserAgentSettings after initialization because empty
6744 // entries get overridden by Init().
6745 context.set_http_user_agent_settings(NULL);
6746
6747 struct {
6748 const char* request;
6749 const char* expected_response;
6750 } tests[] = { { "echoheader?Accept-Language", "None" },
6751 { "echoheader?Accept-Charset", "None" },
6752 { "echoheader?User-Agent", "" } };
6753
viettrungluue4a8b882014-10-16 06:17:386754 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:436755 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196756 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366757 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196758 req->Start();
[email protected]255620da2013-08-19 13:14:296759 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:436760 EXPECT_EQ(tests[i].expected_response, d.data_received())
6761 << " Request = \"" << tests[i].request << "\"";
6762 }
6763}
6764
[email protected]5033ab82013-03-22 20:17:466765// Make sure that URLRequest passes on its priority updates to
6766// newly-created jobs after the first one.
6767TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6768 ASSERT_TRUE(test_server_.Start());
6769
6770 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196771 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366772 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196773 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:466774
6775 scoped_refptr<URLRequestRedirectJob> redirect_job =
6776 new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196777 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096778 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:506779 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:466780
[email protected]f7022f32014-08-21 16:32:196781 req->SetPriority(LOW);
6782 req->Start();
6783 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:466784
6785 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:196786 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:506787 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:466788
6789 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:296790 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:466791 EXPECT_EQ(LOW, job->priority());
6792}
6793
[email protected]80abdad2014-03-15 00:20:546794// Check that creating a network request while entering/exiting suspend mode
6795// fails as it should. This is the only case where an HttpTransactionFactory
6796// does not return an HttpTransaction.
6797TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6798 // Create a new HttpNetworkLayer that thinks it's suspended.
6799 HttpNetworkSession::Params params;
6800 params.host_resolver = default_context_.host_resolver();
6801 params.cert_verifier = default_context_.cert_verifier();
6802 params.transport_security_state = default_context_.transport_security_state();
6803 params.proxy_service = default_context_.proxy_service();
6804 params.ssl_config_service = default_context_.ssl_config_service();
6805 params.http_auth_handler_factory =
6806 default_context_.http_auth_handler_factory();
6807 params.network_delegate = &default_network_delegate_;
6808 params.http_server_properties = default_context_.http_server_properties();
6809 scoped_ptr<HttpNetworkLayer> network_layer(
6810 new HttpNetworkLayer(new HttpNetworkSession(params)));
6811 network_layer->OnSuspend();
6812
6813 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6814 HttpCache::DefaultBackend::InMemory(0));
6815
6816 TestURLRequestContext context(true);
6817 context.set_http_transaction_factory(&http_cache);
6818 context.Init();
6819
6820 TestDelegate d;
davidben151423e2015-03-23 18:48:366821 scoped_ptr<URLRequest> req(
6822 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196823 req->Start();
[email protected]80abdad2014-03-15 00:20:546824 base::RunLoop().Run();
6825
6826 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196827 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6828 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546829}
6830
6831// Check that creating a network request while entering/exiting suspend mode
6832// fails as it should in the case there is no cache. This is the only case
6833// where an HttpTransactionFactory does not return an HttpTransaction.
6834TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6835 // Create a new HttpNetworkLayer that thinks it's suspended.
6836 HttpNetworkSession::Params params;
6837 params.host_resolver = default_context_.host_resolver();
6838 params.cert_verifier = default_context_.cert_verifier();
6839 params.transport_security_state = default_context_.transport_security_state();
6840 params.proxy_service = default_context_.proxy_service();
6841 params.ssl_config_service = default_context_.ssl_config_service();
6842 params.http_auth_handler_factory =
6843 default_context_.http_auth_handler_factory();
6844 params.network_delegate = &default_network_delegate_;
6845 params.http_server_properties = default_context_.http_server_properties();
6846 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6847 network_layer.OnSuspend();
6848
6849 TestURLRequestContext context(true);
6850 context.set_http_transaction_factory(&network_layer);
6851 context.Init();
6852
6853 TestDelegate d;
davidben151423e2015-03-23 18:48:366854 scoped_ptr<URLRequest> req(
6855 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196856 req->Start();
[email protected]80abdad2014-03-15 00:20:546857 base::RunLoop().Run();
6858
6859 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196860 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6861 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546862}
6863
ttuttlec0c828492015-05-15 01:25:556864TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
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
6872 req->Start();
6873 base::RunLoop().Run();
6874
6875 EXPECT_TRUE(req->response_info().network_accessed);
6876}
6877
6878TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
6879 ASSERT_TRUE(test_server_.Start());
6880
6881 // Populate the cache.
6882 TestDelegate d;
6883 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6884 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
6885 req->Start();
6886 base::RunLoop().Run();
6887
6888 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6889 EXPECT_TRUE(req->response_info().network_accessed);
6890 EXPECT_FALSE(req->response_info().was_cached);
6891
6892 req = default_context_.CreateRequest(test_server_.GetURL("cachetime"),
6893 DEFAULT_PRIORITY, &d);
6894 req->Start();
6895 base::RunLoop().Run();
6896
6897 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6898 EXPECT_FALSE(req->response_info().network_accessed);
6899 EXPECT_TRUE(req->response_info().was_cached);
6900}
6901
6902TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
6903 ASSERT_TRUE(test_server_.Start());
6904
6905 TestDelegate d;
6906 GURL test_url(test_server_.GetURL(std::string()));
6907 scoped_ptr<URLRequest> req(
6908 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
6909 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
6910
6911 req->Start();
6912 base::RunLoop().Run();
6913
6914 EXPECT_FALSE(req->response_info().network_accessed);
6915}
6916
bengr1bf8e942014-11-07 01:36:506917class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
6918 public:
6919 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
6920 // ideally remove the dependency on URLRequestTestJob, and maybe move these
6921 // tests into the factory tests.
6922 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
6923 }
6924
6925 void SetUpFactory() override {
6926 interceptor_ = new MockURLRequestInterceptor();
6927 job_factory_.reset(new URLRequestInterceptingJobFactory(
6928 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
6929 }
6930
6931 MockURLRequestInterceptor* interceptor() const {
6932 return interceptor_;
6933 }
6934
6935 private:
6936 MockURLRequestInterceptor* interceptor_;
6937};
6938
6939TEST_F(URLRequestInterceptorTestHTTP,
6940 NetworkDelegateNotificationOnRedirectIntercept) {
6941 interceptor()->set_intercept_redirect(true);
6942 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
6943 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
6944
6945 ASSERT_TRUE(test_server()->Start());
6946
6947 TestDelegate d;
6948 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:366949 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:506950 req->Start();
6951 base::RunLoop().Run();
6952
6953 EXPECT_TRUE(interceptor()->did_intercept_redirect());
6954 // Check we got one good response
6955 EXPECT_TRUE(req->status().is_success());
6956 if (req->status().is_success())
6957 EXPECT_EQ(200, req->response_headers()->response_code());
6958
6959 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6960 EXPECT_EQ(1, d.response_started_count());
6961 EXPECT_EQ(0, d.received_redirect_count());
6962
6963 EXPECT_EQ(1, default_network_delegate()->created_requests());
6964 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6965 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
6966}
6967
6968TEST_F(URLRequestInterceptorTestHTTP,
6969 NetworkDelegateNotificationOnErrorIntercept) {
6970 // Intercept that error and respond with an OK response.
6971 interceptor()->set_intercept_final_response(true);
6972 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
6973 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
6974 default_network_delegate()->set_can_be_intercepted_on_error(true);
6975
6976 ASSERT_TRUE(test_server()->Start());
6977
6978 TestDelegate d;
6979 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6980 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366981 &d));
bengr1bf8e942014-11-07 01:36:506982 req->set_method("GET");
6983 req->Start();
6984 base::RunLoop().Run();
6985
6986 EXPECT_TRUE(interceptor()->did_intercept_final());
6987
6988 // Check we received one good response.
6989 EXPECT_TRUE(req->status().is_success());
6990 if (req->status().is_success())
6991 EXPECT_EQ(200, req->response_headers()->response_code());
6992 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6993 EXPECT_EQ(1, d.response_started_count());
6994 EXPECT_EQ(0, d.received_redirect_count());
6995
6996 EXPECT_EQ(1, default_network_delegate()->created_requests());
6997 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6998 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
6999}
7000
7001TEST_F(URLRequestInterceptorTestHTTP,
7002 NetworkDelegateNotificationOnResponseIntercept) {
7003 // Intercept that error and respond with an OK response.
7004 interceptor()->set_intercept_final_response(true);
7005
7006 // Intercept with a real URLRequestHttpJob.
7007 interceptor()->set_use_url_request_http_job(true);
7008
7009 ASSERT_TRUE(test_server()->Start());
7010
7011 TestDelegate d;
7012 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:367013 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507014 req->set_method("GET");
7015 req->Start();
7016 base::RunLoop().Run();
7017
7018 EXPECT_TRUE(interceptor()->did_intercept_final());
7019
7020 // Check we received one good response.
7021 EXPECT_TRUE(req->status().is_success());
7022 if (req->status().is_success())
7023 EXPECT_EQ(200, req->response_headers()->response_code());
7024 EXPECT_EQ("hello", d.data_received());
7025 EXPECT_EQ(1, d.response_started_count());
7026 EXPECT_EQ(0, d.received_redirect_count());
7027
7028 EXPECT_EQ(1, default_network_delegate()->created_requests());
7029 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7030 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7031}
7032
mkwst0c5eab872014-11-21 14:18:547033class URLRequestTestReferrerPolicy : public URLRequestTest {
7034 public:
7035 URLRequestTestReferrerPolicy() {}
7036
7037 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
7038 origin_server_.reset(new SpawnedTestServer(
7039 origin_type, SpawnedTestServer::kLocalhost,
7040 origin_type == SpawnedTestServer::TYPE_HTTPS
7041 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477042 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547043 ASSERT_TRUE(origin_server_->Start());
7044 }
7045
7046 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
7047 SpawnedTestServer::Type destination_type) {
7048 origin_server_.reset(new SpawnedTestServer(
7049 origin_type, SpawnedTestServer::kLocalhost,
7050 origin_type == SpawnedTestServer::TYPE_HTTPS
7051 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477052 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547053 ASSERT_TRUE(origin_server_->Start());
7054
7055 destination_server_.reset(new SpawnedTestServer(
7056 destination_type, SpawnedTestServer::kLocalhost,
7057 destination_type == SpawnedTestServer::TYPE_HTTPS
7058 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477059 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547060 ASSERT_TRUE(destination_server_->Start());
7061 }
7062
7063 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7064 const GURL& referrer,
7065 const GURL& expected) {
7066 // Create and execute the request: we'll only have a |destination_server_|
7067 // if the origins are meant to be distinct. Otherwise, we'll use the
7068 // |origin_server_| for both endpoints.
7069 GURL destination_url =
7070 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
7071 : origin_server_->GetURL("echoheader?Referer");
7072 GURL origin_url =
7073 origin_server_->GetURL("server-redirect?" + destination_url.spec());
7074
7075 TestDelegate d;
7076 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367077 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547078 req->set_referrer_policy(policy);
7079 req->SetReferrer(referrer.spec());
7080 req->Start();
7081 base::RunLoop().Run();
7082
7083 EXPECT_EQ(1, d.response_started_count());
7084 EXPECT_EQ(1, d.received_redirect_count());
7085 EXPECT_EQ(destination_url, req->url());
7086 EXPECT_TRUE(req->status().is_success());
7087 EXPECT_EQ(200, req->response_headers()->response_code());
7088
7089 EXPECT_EQ(expected.spec(), req->referrer());
7090 if (expected.is_empty())
7091 EXPECT_EQ("None", d.data_received());
7092 else
7093 EXPECT_EQ(expected.spec(), d.data_received());
7094 }
7095
7096 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
7097
7098 private:
7099 scoped_ptr<SpawnedTestServer> origin_server_;
7100 scoped_ptr<SpawnedTestServer> destination_server_;
7101};
7102
7103TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
7104 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
7105
7106 VerifyReferrerAfterRedirect(
7107 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7108 origin_server()->GetURL("path/to/file.html"),
7109 origin_server()->GetURL("path/to/file.html"));
7110
7111 VerifyReferrerAfterRedirect(
7112 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7113 origin_server()->GetURL("path/to/file.html"),
7114 origin_server()->GetURL("path/to/file.html"));
7115
7116 VerifyReferrerAfterRedirect(
7117 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7118 origin_server()->GetURL("path/to/file.html"),
7119 origin_server()->GetURL("path/to/file.html"));
7120
7121 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7122 origin_server()->GetURL("path/to/file.html"),
7123 origin_server()->GetURL("path/to/file.html"));
7124}
7125
7126TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
7127 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7128 SpawnedTestServer::TYPE_HTTP);
7129
7130 VerifyReferrerAfterRedirect(
7131 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7132 origin_server()->GetURL("path/to/file.html"),
7133 origin_server()->GetURL("path/to/file.html"));
7134
7135 VerifyReferrerAfterRedirect(
7136 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7137 origin_server()->GetURL("path/to/file.html"),
7138 origin_server()->GetURL(std::string()));
7139
7140 VerifyReferrerAfterRedirect(
7141 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7142 origin_server()->GetURL("path/to/file.html"),
7143 origin_server()->GetURL(std::string()));
7144
7145 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7146 origin_server()->GetURL("path/to/file.html"),
7147 origin_server()->GetURL("path/to/file.html"));
7148}
7149
7150TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
7151 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
7152
7153 VerifyReferrerAfterRedirect(
7154 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7155 origin_server()->GetURL("path/to/file.html"),
7156 origin_server()->GetURL("path/to/file.html"));
7157
7158 VerifyReferrerAfterRedirect(
7159 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7160 origin_server()->GetURL("path/to/file.html"),
7161 origin_server()->GetURL("path/to/file.html"));
7162
7163 VerifyReferrerAfterRedirect(
7164 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7165 origin_server()->GetURL("path/to/file.html"),
7166 origin_server()->GetURL("path/to/file.html"));
7167
7168 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7169 origin_server()->GetURL("path/to/file.html"),
7170 origin_server()->GetURL("path/to/file.html"));
7171}
7172
7173TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7174 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7175 SpawnedTestServer::TYPE_HTTPS);
7176
7177 VerifyReferrerAfterRedirect(
7178 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7179 origin_server()->GetURL("path/to/file.html"),
7180 origin_server()->GetURL("path/to/file.html"));
7181
7182 VerifyReferrerAfterRedirect(
7183 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7184 origin_server()->GetURL("path/to/file.html"),
7185 origin_server()->GetURL(std::string()));
7186
7187 VerifyReferrerAfterRedirect(
7188 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7189 origin_server()->GetURL("path/to/file.html"),
7190 origin_server()->GetURL(std::string()));
7191
7192 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7193 origin_server()->GetURL("path/to/file.html"),
7194 origin_server()->GetURL("path/to/file.html"));
7195}
7196
7197TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7198 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7199 SpawnedTestServer::TYPE_HTTPS);
7200
7201 VerifyReferrerAfterRedirect(
7202 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7203 origin_server()->GetURL("path/to/file.html"),
7204 origin_server()->GetURL("path/to/file.html"));
7205
7206 VerifyReferrerAfterRedirect(
7207 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7208 origin_server()->GetURL("path/to/file.html"),
7209 origin_server()->GetURL(std::string()));
7210
7211 VerifyReferrerAfterRedirect(
7212 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7213 origin_server()->GetURL("path/to/file.html"),
7214 origin_server()->GetURL(std::string()));
7215
7216 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7217 origin_server()->GetURL("path/to/file.html"),
7218 origin_server()->GetURL("path/to/file.html"));
7219}
7220
7221TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7222 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7223 SpawnedTestServer::TYPE_HTTP);
7224
7225 VerifyReferrerAfterRedirect(
7226 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7227 origin_server()->GetURL("path/to/file.html"), GURL());
7228
7229 VerifyReferrerAfterRedirect(
7230 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7231 origin_server()->GetURL("path/to/file.html"), GURL());
7232
7233 VerifyReferrerAfterRedirect(
7234 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7235 origin_server()->GetURL("path/to/file.html"),
7236 origin_server()->GetURL(std::string()));
7237
7238 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7239 origin_server()->GetURL("path/to/file.html"),
7240 origin_server()->GetURL("path/to/file.html"));
7241}
7242
[email protected]73e0bba2009-02-19 22:57:097243class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507244 public:
[email protected]ef2bf422012-05-11 03:27:097245 HTTPSRequestTest() : default_context_(true) {
7246 default_context_.set_network_delegate(&default_network_delegate_);
7247 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507248 }
dcheng67be2b1f2014-10-27 21:47:297249 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507250
7251 protected:
[email protected]ceefd7fd2012-11-29 00:36:247252 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097253 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467254};
7255
[email protected]c044616e2013-02-20 02:01:267256TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227257 SpawnedTestServer test_server(
7258 SpawnedTestServer::TYPE_HTTPS,
7259 SpawnedTestServer::kLocalhost,
7260 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117261 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467262
[email protected]ea224582008-12-07 20:25:467263 TestDelegate d;
7264 {
[email protected]f7022f32014-08-21 16:32:197265 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367266 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197267 r->Start();
7268 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467269
[email protected]255620da2013-08-19 13:14:297270 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467271
7272 EXPECT_EQ(1, d.response_started_count());
7273 EXPECT_FALSE(d.received_data_before_response());
7274 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197275 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197276 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197277 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197278 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197279 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467280 }
[email protected]ea224582008-12-07 20:25:467281}
7282
[email protected]5774ada2010-07-15 06:30:547283TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227284 SpawnedTestServer::SSLOptions ssl_options(
7285 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
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 bool err_allowed = true;
7293 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7294 TestDelegate d;
7295 {
7296 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197297 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367298 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337299
[email protected]f7022f32014-08-21 16:32:197300 r->Start();
7301 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337302
[email protected]255620da2013-08-19 13:14:297303 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337304
7305 EXPECT_EQ(1, d.response_started_count());
7306 EXPECT_FALSE(d.received_data_before_response());
7307 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177308 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337309 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197310 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177311 } else {
[email protected]bacff652009-03-31 17:50:337312 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177313 }
[email protected]bacff652009-03-31 17:50:337314 }
7315 }
7316}
7317
[email protected]5774ada2010-07-15 06:30:547318TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227319 SpawnedTestServer::SSLOptions ssl_options(
7320 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7321 SpawnedTestServer test_server(
7322 SpawnedTestServer::TYPE_HTTPS,
7323 ssl_options,
7324 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117325 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337326
7327 // Iterate from false to true, just so that we do the opposite of the
7328 // previous test in order to increase test coverage.
7329 bool err_allowed = false;
7330 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7331 TestDelegate d;
7332 {
7333 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197334 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367335 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337336
[email protected]f7022f32014-08-21 16:32:197337 r->Start();
7338 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337339
[email protected]255620da2013-08-19 13:14:297340 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337341
7342 EXPECT_EQ(1, d.response_started_count());
7343 EXPECT_FALSE(d.received_data_before_response());
7344 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177345 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337346 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197347 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177348 } else {
[email protected]bacff652009-03-31 17:50:337349 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177350 }
[email protected]bacff652009-03-31 17:50:337351 }
7352 }
7353}
[email protected]73e0bba2009-02-19 22:57:097354
davidbena4c9d062015-04-03 22:34:257355// Tests that servers which require a deprecated cipher suite still work.
7356TEST_F(HTTPSRequestTest, CipherFallbackTest) {
vishal.b62985ca92015-04-17 08:45:517357 TestNetLog net_log;
davidbena4c9d062015-04-03 22:34:257358 default_context_.set_net_log(&net_log);
7359
7360 SpawnedTestServer::SSLOptions ssl_options;
7361 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
7362 SpawnedTestServer test_server(
7363 SpawnedTestServer::TYPE_HTTPS, ssl_options,
7364 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7365 ASSERT_TRUE(test_server.Start());
7366
7367 TestDelegate d;
7368 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7369 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7370 r->Start();
7371 EXPECT_TRUE(r->is_pending());
7372
7373 base::RunLoop().Run();
7374
7375 EXPECT_EQ(1, d.response_started_count());
7376 EXPECT_FALSE(d.received_data_before_response());
7377 EXPECT_NE(0, d.bytes_received());
7378 CheckSSLInfo(r->ssl_info());
7379 EXPECT_EQ(test_server.host_port_pair().host(), r->GetSocketAddress().host());
7380 EXPECT_EQ(test_server.host_port_pair().port(), r->GetSocketAddress().port());
7381
7382 // No version downgrade should have been necessary.
7383 EXPECT_FALSE(r->ssl_info().connection_status &
7384 SSL_CONNECTION_VERSION_FALLBACK);
7385 int expected_version = SSL_CONNECTION_VERSION_TLS1_2;
7386 if (SSLClientSocket::GetMaxSupportedSSLVersion() <
7387 SSL_PROTOCOL_VERSION_TLS1_2) {
7388 expected_version = SSL_CONNECTION_VERSION_TLS1_1;
7389 }
7390 EXPECT_EQ(expected_version,
7391 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
7392
mmenke43758e62015-05-04 21:09:467393 TestNetLogEntry::List entries;
davidbena4c9d062015-04-03 22:34:257394 net_log.GetEntries(&entries);
7395 ExpectLogContainsSomewhere(entries, 0, NetLog::TYPE_SSL_CIPHER_FALLBACK,
7396 NetLog::PHASE_NONE);
7397}
7398
[email protected]316c1e5e2012-09-12 15:17:447399// This tests that a load of www.google.com with a certificate error sets
7400// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7401// the interstitial to be fatal.
7402TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227403 SpawnedTestServer::SSLOptions ssl_options(
7404 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7405 SpawnedTestServer test_server(
7406 SpawnedTestServer::TYPE_HTTPS,
7407 ssl_options,
7408 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447409 ASSERT_TRUE(test_server.Start());
7410
7411 // We require that the URL be www.google.com in order to pick up the
7412 // preloaded HSTS entries in the TransportSecurityState. This means that we
7413 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247414 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447415
7416 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247417 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447418 TestURLRequestContext context(true);
7419 context.set_network_delegate(&network_delegate);
7420 context.set_host_resolver(&host_resolver);
7421 TransportSecurityState transport_security_state;
7422 context.set_transport_security_state(&transport_security_state);
7423 context.Init();
7424
7425 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197426 scoped_ptr<URLRequest> r(context.CreateRequest(
7427 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367428 test_server.host_port_pair().port())),
7429 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447430
[email protected]f7022f32014-08-21 16:32:197431 r->Start();
7432 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447433
[email protected]255620da2013-08-19 13:14:297434 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447435
7436 EXPECT_EQ(1, d.response_started_count());
7437 EXPECT_FALSE(d.received_data_before_response());
7438 EXPECT_TRUE(d.have_certificate_errors());
7439 EXPECT_TRUE(d.certificate_errors_are_fatal());
7440}
7441
7442// This tests that cached HTTPS page loads do not cause any updates to the
7443// TransportSecurityState.
7444TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7445 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7446 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227447 SpawnedTestServer::SSLOptions ssl_options(
7448 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7449 SpawnedTestServer test_server(
7450 SpawnedTestServer::TYPE_HTTPS,
7451 ssl_options,
7452 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447453 ASSERT_TRUE(test_server.Start());
7454
[email protected]9e6968d2014-05-07 21:46:267455 // We require that the URL be www.google.com in order to pick up the static
7456 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7457 // that we have to use a MockHostResolver in order to direct www.google.com to
7458 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447459
7460 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247461 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447462 TestURLRequestContext context(true);
7463 context.set_network_delegate(&network_delegate);
7464 context.set_host_resolver(&host_resolver);
7465 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267466
7467 TransportSecurityState::DomainState static_domain_state;
7468 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127469 "www.google.com", &static_domain_state));
[email protected]316c1e5e2012-09-12 15:17:447470 context.set_transport_security_state(&transport_security_state);
7471 context.Init();
7472
[email protected]9e6968d2014-05-07 21:46:267473 TransportSecurityState::DomainState dynamic_domain_state;
7474 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7475 "www.google.com", &dynamic_domain_state));
7476
[email protected]316c1e5e2012-09-12 15:17:447477 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197478 scoped_ptr<URLRequest> r(context.CreateRequest(
7479 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367480 test_server.host_port_pair().port())),
7481 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447482
[email protected]f7022f32014-08-21 16:32:197483 r->Start();
7484 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447485
[email protected]255620da2013-08-19 13:14:297486 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447487
7488 EXPECT_EQ(1, d.response_started_count());
7489 EXPECT_FALSE(d.received_data_before_response());
7490 EXPECT_TRUE(d.have_certificate_errors());
7491 EXPECT_TRUE(d.certificate_errors_are_fatal());
7492
[email protected]9e6968d2014-05-07 21:46:267493 // Get a fresh copy of the states, and check that they haven't changed.
7494 TransportSecurityState::DomainState new_static_domain_state;
7495 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127496 "www.google.com", &new_static_domain_state));
[email protected]9e6968d2014-05-07 21:46:267497 TransportSecurityState::DomainState new_dynamic_domain_state;
7498 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7499 "www.google.com", &new_dynamic_domain_state));
7500
7501 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
7502 static_domain_state.sts.upgrade_mode);
7503 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
7504 static_domain_state.sts.include_subdomains);
7505 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
7506 static_domain_state.pkp.include_subdomains);
7507 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
7508 static_domain_state.pkp.spki_hashes));
7509 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
7510 static_domain_state.pkp.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:447511}
7512
[email protected]8ccc69f2012-11-28 19:52:147513// Make sure HSTS preserves a POST request's method and body.
7514TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7515 static const char kData[] = "hello world";
7516
[email protected]ce7d0cbc2013-05-03 18:57:227517 SpawnedTestServer::SSLOptions ssl_options(
7518 SpawnedTestServer::SSLOptions::CERT_OK);
7519 SpawnedTestServer test_server(
7520 SpawnedTestServer::TYPE_HTTPS,
7521 ssl_options,
7522 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:147523 ASSERT_TRUE(test_server.Start());
7524
7525
7526 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7527 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:227528 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7529 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:147530 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:147531
7532 // Force https for www.somewhere.com.
7533 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:207534 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7535 bool include_subdomains = false;
7536 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7537 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:147538
7539 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7540
7541 TestURLRequestContext context(true);
7542 context.set_host_resolver(&host_resolver);
7543 context.set_transport_security_state(&transport_security_state);
7544 context.set_network_delegate(&network_delegate);
7545 context.Init();
7546
7547 TestDelegate d;
7548 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7549 // cause a certificate error. Ignore the error.
7550 d.set_allow_certificate_errors(true);
7551
[email protected]f7022f32014-08-21 16:32:197552 scoped_ptr<URLRequest> req(context.CreateRequest(
7553 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:367554 test_server.host_port_pair().port())),
7555 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197556 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077557 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:147558
[email protected]f7022f32014-08-21 16:32:197559 req->Start();
[email protected]255620da2013-08-19 13:14:297560 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:147561
[email protected]f7022f32014-08-21 16:32:197562 EXPECT_EQ("https", req->url().scheme());
7563 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:147564 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:407565
7566 LoadTimingInfo load_timing_info;
7567 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7568 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7569 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:147570}
7571
rob4e0be1f2014-09-11 23:40:227572// Make sure that the CORS headers are added to cross-origin HSTS redirects.
7573TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7574 static const char kOriginHeaderValue[] = "http://www.example.com";
7575
7576 SpawnedTestServer::SSLOptions ssl_options(
7577 SpawnedTestServer::SSLOptions::CERT_OK);
7578 SpawnedTestServer test_server(
7579 SpawnedTestServer::TYPE_HTTPS,
7580 ssl_options,
7581 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7582 ASSERT_TRUE(test_server.Start());
7583
7584 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7585 // address, so a MockHostResolver is needed to redirect example.net to the
7586 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7587 MockHostResolver host_resolver;
7588
7589 TransportSecurityState transport_security_state;
7590 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7591 bool include_subdomains = false;
7592 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7593
7594 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7595
7596 MockCertVerifier cert_verifier;
7597 cert_verifier.set_default_result(OK);
7598
7599 TestURLRequestContext context(true);
7600 context.set_host_resolver(&host_resolver);
7601 context.set_transport_security_state(&transport_security_state);
7602 context.set_network_delegate(&network_delegate);
7603 context.set_cert_verifier(&cert_verifier);
7604 context.Init();
7605
7606 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7607 test_server.host_port_pair().port()));
7608 url::Replacements<char> replacements;
7609 const char kNewScheme[] = "https";
7610 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7611 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7612
7613 TestDelegate d;
7614 // Quit on redirect to allow response header inspection upon redirect.
7615 d.set_quit_on_redirect(true);
7616
davidben151423e2015-03-23 18:48:367617 scoped_ptr<URLRequest> req(
7618 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:227619 // Set Origin header to simulate a cross-origin request.
7620 HttpRequestHeaders request_headers;
7621 request_headers.SetHeader("Origin", kOriginHeaderValue);
7622 req->SetExtraRequestHeaders(request_headers);
7623
7624 req->Start();
7625 base::RunLoop().Run();
7626
7627 EXPECT_EQ(1, d.received_redirect_count());
7628
7629 const HttpResponseHeaders* headers = req->response_headers();
7630 std::string redirect_location;
7631 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7632 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7633
7634 std::string received_cors_header;
7635 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7636 &received_cors_header));
7637 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7638}
7639
Adam Ricecb76ac62015-02-20 05:33:257640// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
7641// are performed in net/websockets/websocket_end_to_end_test.cc.
7642TEST(WebSocketURLRequestTest, HSTSApplied) {
7643 TestNetworkDelegate network_delegate;
7644 TransportSecurityState transport_security_state;
7645 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7646 bool include_subdomains = false;
7647 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7648 TestURLRequestContext context(true);
7649 context.set_transport_security_state(&transport_security_state);
7650 context.set_network_delegate(&network_delegate);
7651 context.Init();
7652 GURL ws_url("ws://example.net/echo");
7653 TestDelegate delegate;
7654 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367655 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:257656 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
7657 EXPECT_TRUE(ws_url.SchemeIs("wss"));
7658}
7659
[email protected]316c1e5e2012-09-12 15:17:447660namespace {
7661
7662class SSLClientAuthTestDelegate : public TestDelegate {
7663 public:
7664 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7665 }
dchengb03027d2014-10-21 12:00:207666 void OnCertificateRequested(URLRequest* request,
7667 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:447668 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:347669 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:447670 }
7671 int on_certificate_requested_count() {
7672 return on_certificate_requested_count_;
7673 }
7674 private:
7675 int on_certificate_requested_count_;
7676};
7677
7678} // namespace
7679
7680// TODO(davidben): Test the rest of the code. Specifically,
7681// - Filtering which certificates to select.
7682// - Sending a certificate back.
7683// - Getting a certificate request in an SSL renegotiation sending the
7684// HTTP request.
7685TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227686 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447687 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:227688 SpawnedTestServer test_server(
7689 SpawnedTestServer::TYPE_HTTPS,
7690 ssl_options,
7691 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447692 ASSERT_TRUE(test_server.Start());
7693
7694 SSLClientAuthTestDelegate d;
7695 {
[email protected]f7022f32014-08-21 16:32:197696 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367697 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447698
[email protected]f7022f32014-08-21 16:32:197699 r->Start();
7700 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447701
[email protected]255620da2013-08-19 13:14:297702 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447703
7704 EXPECT_EQ(1, d.on_certificate_requested_count());
7705 EXPECT_FALSE(d.received_data_before_response());
7706 EXPECT_EQ(0, d.bytes_received());
7707
7708 // Send no certificate.
7709 // TODO(davidben): Get temporary client cert import (with keys) working on
7710 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:197711 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:447712
[email protected]255620da2013-08-19 13:14:297713 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447714
7715 EXPECT_EQ(1, d.response_started_count());
7716 EXPECT_FALSE(d.received_data_before_response());
7717 EXPECT_NE(0, d.bytes_received());
7718 }
7719}
7720
7721TEST_F(HTTPSRequestTest, ResumeTest) {
7722 // Test that we attempt a session resume when making two connections to the
7723 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:227724 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447725 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227726 SpawnedTestServer test_server(
7727 SpawnedTestServer::TYPE_HTTPS,
7728 ssl_options,
7729 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447730 ASSERT_TRUE(test_server.Start());
7731
7732 SSLClientSocket::ClearSessionCache();
7733
7734 {
7735 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197736 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367737 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447738
[email protected]f7022f32014-08-21 16:32:197739 r->Start();
7740 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447741
[email protected]255620da2013-08-19 13:14:297742 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447743
7744 EXPECT_EQ(1, d.response_started_count());
7745 }
7746
7747 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7748 CloseAllConnections();
7749
7750 {
7751 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197752 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367753 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447754
[email protected]f7022f32014-08-21 16:32:197755 r->Start();
7756 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447757
[email protected]255620da2013-08-19 13:14:297758 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447759
7760 // The response will look like;
7761 // insert abc
7762 // lookup abc
7763 // insert xyz
7764 //
7765 // With a newline at the end which makes the split think that there are
7766 // four lines.
7767
7768 EXPECT_EQ(1, d.response_started_count());
7769 std::vector<std::string> lines;
7770 base::SplitString(d.data_received(), '\n', &lines);
7771 ASSERT_EQ(4u, lines.size()) << d.data_received();
7772
7773 std::string session_id;
7774
7775 for (size_t i = 0; i < 2; i++) {
7776 std::vector<std::string> parts;
7777 base::SplitString(lines[i], '\t', &parts);
7778 ASSERT_EQ(2u, parts.size());
7779 if (i == 0) {
7780 EXPECT_EQ("insert", parts[0]);
7781 session_id = parts[1];
7782 } else {
7783 EXPECT_EQ("lookup", parts[0]);
7784 EXPECT_EQ(session_id, parts[1]);
7785 }
7786 }
7787 }
7788}
7789
Adam Langley32352ad2014-10-14 22:31:007790// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7791// the result of fetching "ssl-session-cache" from the test server, indicates
7792// that exactly two different sessions were inserted, with no lookups etc.
7793static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7794 std::vector<std::string> lines;
7795 base::SplitString(session_info, '\n', &lines);
7796 ASSERT_EQ(3u, lines.size()) << session_info;
7797
7798 std::string session_id;
7799 for (size_t i = 0; i < 2; i++) {
7800 std::vector<std::string> parts;
7801 base::SplitString(lines[i], '\t', &parts);
7802 ASSERT_EQ(2u, parts.size());
7803 EXPECT_EQ("insert", parts[0]);
7804 if (i == 0) {
7805 session_id = parts[1];
7806 } else {
7807 EXPECT_NE(session_id, parts[1]);
7808 }
7809 }
7810}
7811
[email protected]316c1e5e2012-09-12 15:17:447812TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7813 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7814 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:227815 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447816 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227817 SpawnedTestServer test_server(
7818 SpawnedTestServer::TYPE_HTTPS,
7819 ssl_options,
7820 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447821 ASSERT_TRUE(test_server.Start());
7822
7823 SSLClientSocket::ClearSessionCache();
7824
7825 {
7826 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197827 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367828 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447829
[email protected]f7022f32014-08-21 16:32:197830 r->Start();
7831 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447832
[email protected]255620da2013-08-19 13:14:297833 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447834
7835 EXPECT_EQ(1, d.response_started_count());
7836 }
7837
7838 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7839 HttpNetworkSession::Params params;
7840 params.host_resolver = default_context_.host_resolver();
7841 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:117842 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:447843 params.proxy_service = default_context_.proxy_service();
7844 params.ssl_config_service = default_context_.ssl_config_service();
7845 params.http_auth_handler_factory =
7846 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:417847 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:447848 params.http_server_properties = default_context_.http_server_properties();
7849 params.ssl_session_cache_shard = "alternate";
7850
[email protected]cba24642014-08-15 20:49:597851 scoped_ptr<HttpCache> cache(new HttpCache(
7852 new HttpNetworkSession(params),
7853 HttpCache::DefaultBackend::InMemory(0)));
[email protected]316c1e5e2012-09-12 15:17:447854
7855 default_context_.set_http_transaction_factory(cache.get());
7856
7857 {
7858 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197859 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367860 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447861
[email protected]f7022f32014-08-21 16:32:197862 r->Start();
7863 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447864
[email protected]255620da2013-08-19 13:14:297865 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447866
7867 // The response will look like;
7868 // insert abc
7869 // insert xyz
7870 //
7871 // With a newline at the end which makes the split think that there are
7872 // three lines.
7873
7874 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:007875 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447876 }
7877}
7878
davidben8ecc3072014-09-03 23:19:097879#if defined(OS_WIN)
7880
7881namespace {
7882
7883bool IsECDSACipherSuite(uint16_t cipher_suite) {
7884 const char* key_exchange;
7885 const char* cipher;
7886 const char* mac;
7887 bool is_aead;
7888 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7889 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7890}
7891
7892} // namespace
7893
7894// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7895// verified.
davidben9399c952014-10-07 04:09:117896TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:097897 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7898 LOG(INFO) << "Skipping test on this version.";
7899 return;
7900 }
7901
7902 SpawnedTestServer test_server(
7903 SpawnedTestServer::TYPE_HTTPS,
7904 SpawnedTestServer::kLocalhost,
7905 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7906 ASSERT_TRUE(test_server.Start());
7907
7908 TestDelegate d;
7909 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367910 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:097911 r->Start();
7912 EXPECT_TRUE(r->is_pending());
7913
7914 base::RunLoop().Run();
7915
7916 EXPECT_EQ(1, d.response_started_count());
7917 std::vector<std::string> lines;
7918 base::SplitString(d.data_received(), '\n', &lines);
7919
7920 for (size_t i = 0; i < lines.size(); i++) {
7921 int cipher_suite;
7922 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7923 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7924 << "ClientHello advertised " << cipher_suite;
7925 }
7926}
7927
7928#endif // OS_WIN
7929
Adam Langley32352ad2014-10-14 22:31:007930class TestSSLConfigService : public SSLConfigService {
7931 public:
7932 TestSSLConfigService(bool ev_enabled,
7933 bool online_rev_checking,
7934 bool rev_checking_required_local_anchors)
7935 : ev_enabled_(ev_enabled),
7936 online_rev_checking_(online_rev_checking),
7937 rev_checking_required_local_anchors_(
7938 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:027939 min_version_(kDefaultSSLVersionMin),
7940 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7941
7942 void set_min_version(uint16 version) {
7943 min_version_ = version;
7944 }
Adam Langley32352ad2014-10-14 22:31:007945
7946 void set_fallback_min_version(uint16 version) {
7947 fallback_min_version_ = version;
7948 }
7949
7950 // SSLConfigService:
dchengb03027d2014-10-21 12:00:207951 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:007952 *config = SSLConfig();
7953 config->rev_checking_enabled = online_rev_checking_;
7954 config->verify_ev_cert = ev_enabled_;
7955 config->rev_checking_required_local_anchors =
7956 rev_checking_required_local_anchors_;
7957 if (fallback_min_version_) {
7958 config->version_fallback_min = fallback_min_version_;
7959 }
Adam Langleyac6f24b42014-10-31 20:24:027960 if (min_version_) {
7961 config->version_min = min_version_;
7962 }
Adam Langley32352ad2014-10-14 22:31:007963 }
7964
7965 protected:
dchengb03027d2014-10-21 12:00:207966 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:007967
7968 private:
7969 const bool ev_enabled_;
7970 const bool online_rev_checking_;
7971 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:027972 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:007973 uint16 fallback_min_version_;
7974};
7975
7976class FallbackTestURLRequestContext : public TestURLRequestContext {
7977 public:
7978 explicit FallbackTestURLRequestContext(bool delay_initialization)
7979 : TestURLRequestContext(delay_initialization) {}
7980
7981 void set_fallback_min_version(uint16 version) {
7982 TestSSLConfigService *ssl_config_service =
7983 new TestSSLConfigService(true /* check for EV */,
7984 false /* online revocation checking */,
7985 false /* require rev. checking for local
7986 anchors */);
Adam Langley32352ad2014-10-14 22:31:007987 ssl_config_service->set_fallback_min_version(version);
7988 set_ssl_config_service(ssl_config_service);
7989 }
7990};
7991
[email protected]48d2b7c52014-06-27 01:16:557992class HTTPSFallbackTest : public testing::Test {
7993 public:
Adam Langley32352ad2014-10-14 22:31:007994 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:297995 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:557996
7997 protected:
7998 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
7999 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008000 context_.Init();
8001 delegate_.set_allow_certificate_errors(true);
8002
[email protected]48d2b7c52014-06-27 01:16:558003 SpawnedTestServer test_server(
8004 SpawnedTestServer::TYPE_HTTPS,
8005 ssl_options,
8006 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8007 ASSERT_TRUE(test_server.Start());
8008
davidben151423e2015-03-23 18:48:368009 request_ = context_.CreateRequest(test_server.GetURL(std::string()),
8010 DEFAULT_PRIORITY, &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558011 request_->Start();
8012
8013 base::RunLoop().Run();
8014 }
8015
Adam Langley32352ad2014-10-14 22:31:008016 void set_fallback_min_version(uint16 version) {
8017 context_.set_fallback_min_version(version);
8018 }
8019
[email protected]48d2b7c52014-06-27 01:16:558020 void ExpectConnection(int version) {
8021 EXPECT_EQ(1, delegate_.response_started_count());
8022 EXPECT_NE(0, delegate_.bytes_received());
8023 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8024 request_->ssl_info().connection_status));
8025 EXPECT_TRUE(request_->ssl_info().connection_status &
8026 SSL_CONNECTION_VERSION_FALLBACK);
8027 }
8028
8029 void ExpectFailure(int error) {
8030 EXPECT_EQ(1, delegate_.response_started_count());
8031 EXPECT_FALSE(request_->status().is_success());
8032 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8033 EXPECT_EQ(error, request_->status().error());
8034 }
8035
8036 private:
8037 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008038 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558039 scoped_ptr<URLRequest> request_;
8040};
8041
8042// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
8043// than necessary.
8044TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
8045 SpawnedTestServer::SSLOptions ssl_options(
8046 SpawnedTestServer::SSLOptions::CERT_OK);
8047 ssl_options.tls_intolerant =
8048 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8049
8050 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8051 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
8052}
8053
8054// This test is disabled on Android because the remote test server doesn't cause
8055// a TCP reset.
8056#if !defined(OS_ANDROID)
8057// Tests fallback to TLS 1.0 on connection reset.
8058TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
8059 SpawnedTestServer::SSLOptions ssl_options(
8060 SpawnedTestServer::SSLOptions::CERT_OK);
8061 ssl_options.tls_intolerant =
8062 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8063 ssl_options.tls_intolerance_type =
8064 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8065
8066 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8067 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
8068}
8069#endif // !OS_ANDROID
8070
[email protected]12833302014-07-02 01:57:318071// Tests that we don't fallback on handshake failure with servers that implement
8072// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558073TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558074 SpawnedTestServer::SSLOptions ssl_options(
8075 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438076 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558077 // a version fallback.
8078 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438079 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558080 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8081 // connections are rejected.
8082 ssl_options.fallback_scsv_enabled = true;
8083
8084 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8085
8086 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8087 // intolerance. If the fallback SCSV is processed when the original error
8088 // that caused the fallback should be returned, which should be
8089 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8090 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8091}
8092
[email protected]12833302014-07-02 01:57:318093// Tests that we don't fallback on connection closed with servers that implement
8094// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318095TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318096 SpawnedTestServer::SSLOptions ssl_options(
8097 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438098 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318099 // a version fallback.
8100 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438101 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318102 ssl_options.tls_intolerance_type =
8103 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8104 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8105 // connections are rejected.
8106 ssl_options.fallback_scsv_enabled = true;
8107
8108 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8109
8110 // The original error should be replayed on rejected fallback.
8111 ExpectFailure(ERR_CONNECTION_CLOSED);
8112}
8113
davidbenb937d6c2015-05-14 04:53:428114// Tests that the SSLv3 fallback doesn't happen.
[email protected]48d2b7c52014-06-27 01:16:558115TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
8116 SpawnedTestServer::SSLOptions ssl_options(
8117 SpawnedTestServer::SSLOptions::CERT_OK);
8118 ssl_options.tls_intolerant =
8119 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8120
8121 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
Adam Langleyac6f24b42014-10-31 20:24:028122 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
Adam Langley32352ad2014-10-14 22:31:008123}
8124
davidbenb937d6c2015-05-14 04:53:428125// Tests that the TLSv1 fallback triggers on closed connections.
[email protected]48d2b7c52014-06-27 01:16:558126TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
8127 SpawnedTestServer::SSLOptions ssl_options(
8128 SpawnedTestServer::SSLOptions::CERT_OK);
8129 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428130 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558131 ssl_options.tls_intolerance_type =
8132 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
[email protected]48d2b7c52014-06-27 01:16:558133
8134 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb937d6c2015-05-14 04:53:428135 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
[email protected]48d2b7c52014-06-27 01:16:558136}
8137
davidbenb937d6c2015-05-14 04:53:428138// Test that fallback probe connections don't cause sessions to be cached.
8139TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008140 SpawnedTestServer::SSLOptions ssl_options(
8141 SpawnedTestServer::SSLOptions::CERT_OK);
8142 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428143 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008144 ssl_options.tls_intolerance_type =
8145 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8146 ssl_options.record_resume = true;
8147
8148 SpawnedTestServer test_server(
8149 SpawnedTestServer::TYPE_HTTPS,
8150 ssl_options,
8151 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8152 ASSERT_TRUE(test_server.Start());
8153
8154 SSLClientSocket::ClearSessionCache();
8155
davidbenb937d6c2015-05-14 04:53:428156 // Make a connection that does a probe fallback to TLSv1 but fails because
8157 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008158 // be inserted locally.
8159 {
8160 TestDelegate delegate;
8161 FallbackTestURLRequestContext context(true);
8162
davidbenb937d6c2015-05-14 04:53:428163 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008164 context.Init();
8165 scoped_ptr<URLRequest> request(context.CreateRequest(
davidben151423e2015-03-23 18:48:368166 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008167 request->Start();
8168
8169 base::RunLoop().Run();
8170
8171 EXPECT_EQ(1, delegate.response_started_count());
8172 EXPECT_FALSE(request->status().is_success());
8173 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8174 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8175 request->status().error());
8176 }
8177
davidbenb937d6c2015-05-14 04:53:428178 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008179 {
8180 TestDelegate delegate;
8181 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428182 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008183
8184 context.Init();
davidben151423e2015-03-23 18:48:368185 scoped_ptr<URLRequest> request(context.CreateRequest(
8186 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008187 request->Start();
8188
8189 base::RunLoop().Run();
8190
8191 EXPECT_EQ(1, delegate.response_started_count());
8192 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428193 EXPECT_EQ(
8194 SSL_CONNECTION_VERSION_TLS1,
8195 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008196 EXPECT_TRUE(request->ssl_info().connection_status &
8197 SSL_CONNECTION_VERSION_FALLBACK);
8198
8199 std::vector<std::string> lines;
8200 // If no sessions were cached then the server should have seen two sessions
8201 // inserted with no lookups.
8202 AssertTwoDistinctSessionsInserted(delegate.data_received());
8203 }
8204}
8205
[email protected]a8fed1742013-12-27 02:14:248206class HTTPSSessionTest : public testing::Test {
8207 public:
8208 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598209 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248210
8211 default_context_.set_network_delegate(&default_network_delegate_);
8212 default_context_.set_cert_verifier(&cert_verifier_);
8213 default_context_.Init();
8214 }
dcheng67be2b1f2014-10-27 21:47:298215 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248216
8217 protected:
8218 MockCertVerifier cert_verifier_;
8219 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8220 TestURLRequestContext default_context_;
8221};
8222
8223// Tests that session resumption is not attempted if an invalid certificate
8224// is presented.
8225TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8226 SpawnedTestServer::SSLOptions ssl_options;
8227 ssl_options.record_resume = true;
8228 SpawnedTestServer test_server(
8229 SpawnedTestServer::TYPE_HTTPS,
8230 ssl_options,
8231 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8232 ASSERT_TRUE(test_server.Start());
8233
8234 SSLClientSocket::ClearSessionCache();
8235
8236 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598237 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248238 {
8239 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198240 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368241 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248242
[email protected]f7022f32014-08-21 16:32:198243 r->Start();
8244 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248245
8246 base::RunLoop().Run();
8247
8248 EXPECT_EQ(1, d.response_started_count());
8249 }
8250
8251 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8252 CloseAllConnections();
8253
8254 // Now change the certificate to be acceptable (so that the response is
8255 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598256 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248257 {
8258 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198259 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368260 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248261
[email protected]f7022f32014-08-21 16:32:198262 r->Start();
8263 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248264
8265 base::RunLoop().Run();
8266
8267 // The response will look like;
8268 // insert abc
8269 // insert xyz
8270 //
8271 // With a newline at the end which makes the split think that there are
8272 // three lines.
8273 //
8274 // If a session was presented (eg: a bug), then the response would look
8275 // like;
8276 // insert abc
8277 // lookup abc
8278 // insert xyz
8279
8280 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008281 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248282 }
8283}
8284
[email protected]dffe8242012-03-20 15:14:278285// This the fingerprint of the "Testing CA" certificate used by the testserver.
8286// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268287static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278288 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8289 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8290
[email protected]51523f52013-07-31 21:57:288291// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8292// testserver.
8293static const SHA256HashValue kOCSPTestCertSPKI = { {
8294 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8295 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8296 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8297 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8298} };
8299
[email protected]dffe8242012-03-20 15:14:278300// This is the policy OID contained in the certificates that testserver
8301// generates.
8302static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8303
8304class HTTPSOCSPTest : public HTTPSRequestTest {
8305 public:
8306 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098307 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088308 ev_test_policy_(
8309 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8310 kOCSPTestCertFingerprint,
8311 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028312 }
8313
dcheng67be2b1f2014-10-27 21:47:298314 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098315 SetupContext(&context_);
8316 context_.Init();
[email protected]dffe8242012-03-20 15:14:278317
[email protected]cba24642014-08-15 20:49:598318 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208319 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428320 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508321 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278322
davidben71f35ff2015-04-17 20:54:488323#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098324 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278325 EnsureNSSHttpIOInit();
8326#endif
8327 }
8328
[email protected]ce7d0cbc2013-05-03 18:57:228329 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278330 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538331 // We always overwrite out_cert_status.
8332 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228333 SpawnedTestServer test_server(
8334 SpawnedTestServer::TYPE_HTTPS,
8335 ssl_options,
8336 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278337 ASSERT_TRUE(test_server.Start());
8338
8339 TestDelegate d;
8340 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:198341 scoped_ptr<URLRequest> r(context_.CreateRequest(
davidben151423e2015-03-23 18:48:368342 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198343 r->Start();
[email protected]dffe8242012-03-20 15:14:278344
[email protected]255620da2013-08-19 13:14:298345 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278346
8347 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198348 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278349 }
8350
dcheng67be2b1f2014-10-27 21:47:298351 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488352#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278353 ShutdownNSSHttpIO();
8354#endif
8355 }
8356
[email protected]a13234c2012-03-20 21:45:028357 protected:
8358 // SetupContext configures the URLRequestContext that will be used for making
8359 // connetions to testserver. This can be overridden in test subclasses for
8360 // different behaviour.
8361 virtual void SetupContext(URLRequestContext* context) {
8362 context->set_ssl_config_service(
8363 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208364 true /* online revocation checking */,
8365 false /* require rev. checking for local
8366 anchors */));
[email protected]a13234c2012-03-20 21:45:028367 }
8368
[email protected]dffe8242012-03-20 15:14:278369 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098370 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088371 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278372};
8373
[email protected]a13234c2012-03-20 21:45:028374static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018375#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028376 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8377 // have that ability on other platforms.
8378 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8379#else
8380 return 0;
8381#endif
8382}
8383
[email protected]3a86a712013-07-30 07:16:208384// SystemSupportsHardFailRevocationChecking returns true iff the current
8385// operating system supports revocation checking and can distinguish between
8386// situations where a given certificate lacks any revocation information (eg:
8387// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8388// revocation information cannot be obtained (eg: the CRL was unreachable).
8389// If it does not, then tests which rely on 'hard fail' behaviour should be
8390// skipped.
8391static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:488392#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:208393 return true;
8394#else
8395 return false;
8396#endif
8397}
8398
[email protected]a13234c2012-03-20 21:45:028399// SystemUsesChromiumEVMetadata returns true iff the current operating system
8400// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8401// several tests are effected because our testing EV certificate won't be
8402// recognised as EV.
8403static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328404#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578405 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8406 return false;
[email protected]e1b2d732014-03-28 16:20:328407#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8408 // On OS X and Android, we use the system to tell us whether a certificate is
8409 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018410 return false;
8411#else
8412 return true;
8413#endif
8414}
8415
[email protected]b6f2de32012-08-17 04:35:088416static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008417#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578418 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8419 return false;
8420#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028421 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8422#elif defined(OS_ANDROID)
8423 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8424 return false;
8425#else
8426 return true;
8427#endif
8428}
8429
davidbend1fb2f12014-11-08 02:51:008430static bool SystemSupportsOCSPStapling() {
davidben71f35ff2015-04-17 20:54:488431#if defined(USE_NSS_CERTS)
davidbend1fb2f12014-11-08 02:51:008432 return true;
8433#elif defined(OS_WIN)
8434 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8435#else
8436 return false;
8437#endif
8438}
8439
[email protected]dffe8242012-03-20 15:14:278440TEST_F(HTTPSOCSPTest, Valid) {
8441 if (!SystemSupportsOCSP()) {
8442 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8443 return;
8444 }
8445
[email protected]ce7d0cbc2013-05-03 18:57:228446 SpawnedTestServer::SSLOptions ssl_options(
8447 SpawnedTestServer::SSLOptions::CERT_AUTO);
8448 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278449
[email protected]924e9f92012-12-16 22:00:538450 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128451 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278452
8453 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8454
[email protected]a13234c2012-03-20 21:45:028455 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8456 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278457
8458 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8459}
8460
8461TEST_F(HTTPSOCSPTest, Revoked) {
8462 if (!SystemSupportsOCSP()) {
8463 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8464 return;
8465 }
8466
[email protected]ce7d0cbc2013-05-03 18:57:228467 SpawnedTestServer::SSLOptions ssl_options(
8468 SpawnedTestServer::SSLOptions::CERT_AUTO);
8469 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278470
8471 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128472 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278473
[email protected]a592c0432012-12-01 18:10:298474#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278475 // Doesn't pass on OS X yet for reasons that need to be investigated.
8476 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8477#endif
8478 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8479 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8480}
8481
8482TEST_F(HTTPSOCSPTest, Invalid) {
8483 if (!SystemSupportsOCSP()) {
8484 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8485 return;
8486 }
8487
[email protected]ce7d0cbc2013-05-03 18:57:228488 SpawnedTestServer::SSLOptions ssl_options(
8489 SpawnedTestServer::SSLOptions::CERT_AUTO);
8490 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:278491
[email protected]924e9f92012-12-16 22:00:538492 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128493 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278494
[email protected]a13234c2012-03-20 21:45:028495 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278496 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:278497
8498 // Without a positive OCSP response, we shouldn't show the EV status.
8499 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8500 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8501}
[email protected]a13234c2012-03-20 21:45:028502
davidbend1fb2f12014-11-08 02:51:008503TEST_F(HTTPSOCSPTest, ValidStapled) {
8504 if (!SystemSupportsOCSPStapling()) {
8505 LOG(WARNING)
8506 << "Skipping test because system doesn't support OCSP stapling";
8507 return;
8508 }
8509
8510 SpawnedTestServer::SSLOptions ssl_options(
8511 SpawnedTestServer::SSLOptions::CERT_AUTO);
8512 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8513 ssl_options.staple_ocsp_response = true;
8514 ssl_options.ocsp_server_unavailable = true;
8515
8516 CertStatus cert_status;
8517 DoConnection(ssl_options, &cert_status);
8518
8519 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8520
8521 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8522 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8523
8524 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8525}
8526
davidben6c3191b2014-11-21 22:38:048527// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:488528#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:048529#define MAYBE_RevokedStapled DISABLED_RevokedStapled
8530#else
8531#define MAYBE_RevokedStapled RevokedStapled
8532#endif
8533TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
davidbend1fb2f12014-11-08 02:51:008534 if (!SystemSupportsOCSPStapling()) {
8535 LOG(WARNING)
8536 << "Skipping test because system doesn't support OCSP stapling";
8537 return;
8538 }
8539
8540 SpawnedTestServer::SSLOptions ssl_options(
8541 SpawnedTestServer::SSLOptions::CERT_AUTO);
8542 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8543 ssl_options.staple_ocsp_response = true;
8544 ssl_options.ocsp_server_unavailable = true;
8545
8546 CertStatus cert_status;
8547 DoConnection(ssl_options, &cert_status);
8548
8549 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8550 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8551 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8552}
8553
[email protected]3a86a712013-07-30 07:16:208554class HTTPSHardFailTest : public HTTPSOCSPTest {
8555 protected:
dchengb03027d2014-10-21 12:00:208556 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:208557 context->set_ssl_config_service(
8558 new TestSSLConfigService(false /* check for EV */,
8559 false /* online revocation checking */,
8560 true /* require rev. checking for local
8561 anchors */));
8562 }
8563};
8564
[email protected]3a86a712013-07-30 07:16:208565TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8566 if (!SystemSupportsOCSP()) {
8567 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8568 return;
8569 }
8570
8571 if (!SystemSupportsHardFailRevocationChecking()) {
8572 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8573 << "revocation checking";
8574 return;
8575 }
8576
8577 SpawnedTestServer::SSLOptions ssl_options(
8578 SpawnedTestServer::SSLOptions::CERT_AUTO);
8579 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8580
8581 CertStatus cert_status;
8582 DoConnection(ssl_options, &cert_status);
8583
8584 EXPECT_EQ(CERT_STATUS_REVOKED,
8585 cert_status & CERT_STATUS_REVOKED);
8586
8587 // Without a positive OCSP response, we shouldn't show the EV status.
8588 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8589}
8590
[email protected]a13234c2012-03-20 21:45:028591class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8592 protected:
dchengb03027d2014-10-21 12:00:208593 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028594 context->set_ssl_config_service(
8595 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208596 false /* online revocation checking */,
8597 false /* require rev. checking for local
8598 anchors */));
[email protected]a13234c2012-03-20 21:45:028599 }
8600};
8601
8602TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8603 if (!SystemSupportsOCSP()) {
8604 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8605 return;
8606 }
8607
[email protected]ce7d0cbc2013-05-03 18:57:228608 SpawnedTestServer::SSLOptions ssl_options(
8609 SpawnedTestServer::SSLOptions::CERT_AUTO);
8610 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028611 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8612
[email protected]924e9f92012-12-16 22:00:538613 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128614 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028615
8616 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8617 cert_status & CERT_STATUS_ALL_ERRORS);
8618
8619 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088620 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8621 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028622}
8623
[email protected]be0fff62013-08-29 23:37:488624TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8625 if (!SystemSupportsOCSP()) {
8626 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8627 return;
8628 }
8629
8630 SpawnedTestServer::SSLOptions ssl_options(
8631 SpawnedTestServer::SSLOptions::CERT_AUTO);
8632 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8633 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8634
8635 CertStatus cert_status;
8636 DoConnection(ssl_options, &cert_status);
8637
8638 // Currently only works for Windows. When using NSS or OS X, it's not
8639 // possible to determine whether the check failed because of actual
8640 // revocation or because there was an OCSP failure.
8641#if defined(OS_WIN)
8642 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8643#else
8644 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8645#endif
8646
8647 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8648 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8649 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8650}
8651
[email protected]a13234c2012-03-20 21:45:028652TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8653 if (!SystemSupportsOCSP()) {
8654 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8655 return;
8656 }
8657
[email protected]ce7d0cbc2013-05-03 18:57:228658 SpawnedTestServer::SSLOptions ssl_options(
8659 SpawnedTestServer::SSLOptions::CERT_AUTO);
8660 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:028661 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8662
8663 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128664 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028665
8666 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8667
8668 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8669 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:088670 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8671 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028672}
8673
8674TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8675 if (!SystemSupportsOCSP()) {
8676 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8677 return;
8678 }
8679
[email protected]ce7d0cbc2013-05-03 18:57:228680 SpawnedTestServer::SSLOptions ssl_options(
8681 SpawnedTestServer::SSLOptions::CERT_AUTO);
8682 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028683 SSLConfigService::SetCRLSet(
8684 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8685
8686 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128687 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028688
8689 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8690 cert_status & CERT_STATUS_ALL_ERRORS);
8691
8692 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088693 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8694 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028695}
8696
[email protected]51523f52013-07-31 21:57:288697TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8698 if (!SystemSupportsOCSP()) {
8699 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8700 return;
8701 }
8702
8703 SpawnedTestServer::SSLOptions ssl_options(
8704 SpawnedTestServer::SSLOptions::CERT_AUTO);
8705 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8706 SSLConfigService::SetCRLSet(
8707 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8708 false, &kOCSPTestCertSPKI, "")));
8709
8710 CertStatus cert_status;
8711 DoConnection(ssl_options, &cert_status);
8712
8713 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8714 // revocation check for EV.
8715 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8716 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8717 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8718 EXPECT_FALSE(
8719 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8720}
8721
8722TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8723 if (!SystemSupportsOCSP()) {
8724 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8725 return;
8726 }
8727
[email protected]ce7d0cbc2013-05-03 18:57:228728 SpawnedTestServer::SSLOptions ssl_options(
8729 SpawnedTestServer::SSLOptions::CERT_AUTO);
8730 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028731 SSLConfigService::SetCRLSet(
8732 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8733
[email protected]51523f52013-07-31 21:57:288734 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:128735 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028736
[email protected]51523f52013-07-31 21:57:288737 // Even with a fresh CRLSet, we should still do online revocation checks when
8738 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8739 // test.
8740 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8741 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:028742
[email protected]51523f52013-07-31 21:57:288743 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:028744 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:288745 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028746}
8747
[email protected]b6f2de32012-08-17 04:35:088748TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8749 // Test that when EV verification is requested, but online revocation
8750 // checking is disabled, and the leaf certificate is not in fact EV, that
8751 // no revocation checking actually happens.
8752 if (!SystemSupportsOCSP()) {
8753 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8754 return;
8755 }
8756
8757 // Unmark the certificate's OID as EV, which should disable revocation
8758 // checking (as per the user preference)
8759 ev_test_policy_.reset();
8760
[email protected]ce7d0cbc2013-05-03 18:57:228761 SpawnedTestServer::SSLOptions ssl_options(
8762 SpawnedTestServer::SSLOptions::CERT_AUTO);
8763 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:088764 SSLConfigService::SetCRLSet(
8765 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8766
8767 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128768 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:088769
8770 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8771
8772 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8773 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8774}
8775
[email protected]a13234c2012-03-20 21:45:028776class HTTPSCRLSetTest : public HTTPSOCSPTest {
8777 protected:
dchengb03027d2014-10-21 12:00:208778 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028779 context->set_ssl_config_service(
8780 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208781 false /* online revocation checking */,
8782 false /* require rev. checking for local
8783 anchors */));
[email protected]a13234c2012-03-20 21:45:028784 }
8785};
8786
8787TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:228788 SpawnedTestServer::SSLOptions ssl_options(
8789 SpawnedTestServer::SSLOptions::CERT_AUTO);
8790 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028791 SSLConfigService::SetCRLSet(
8792 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8793
[email protected]924e9f92012-12-16 22:00:538794 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128795 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028796
8797 // If we're not trying EV verification then, even if the CRLSet has expired,
8798 // we don't fall back to online revocation checks.
8799 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8800 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8801 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8802}
[email protected]51523f52013-07-31 21:57:288803
8804TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:308805#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:288806 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8807 return;
8808#endif
8809
8810 SpawnedTestServer::SSLOptions ssl_options(
8811 SpawnedTestServer::SSLOptions::CERT_AUTO);
8812 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8813 ssl_options.cert_serial = 10;
8814 SSLConfigService::SetCRLSet(
8815 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8816 false, &kOCSPTestCertSPKI, "\x0a")));
8817
8818 CertStatus cert_status = 0;
8819 DoConnection(ssl_options, &cert_status);
8820
8821 // If the certificate is recorded as revoked in the CRLSet, that should be
8822 // reflected without online revocation checking.
8823 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8824 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8825 EXPECT_FALSE(
8826 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8827}
[email protected]316c1e5e2012-09-12 15:17:448828#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278829
mmenke9f2ec60c2015-06-01 20:59:478830#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
8831// These tests aren't passing on Android. Either the RemoteTestServer isn't
8832// starting up successfully, or it can't access the test files.
8833// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:318834class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:118835 public:
[email protected]d9fca99a2012-02-24 16:16:208836 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:478837 : ftp_transaction_factory_(&host_resolver_),
8838 test_server_(SpawnedTestServer::TYPE_FTP,
8839 SpawnedTestServer::kLocalhost,
8840 base::FilePath(kTestFilePath)) {
8841 // Can't use |default_context_|'s HostResolver to set up the
8842 // FTPTransactionFactory because it hasn't been created yet.
8843 default_context_.set_host_resolver(&host_resolver_);
8844 }
8845
8846 // URLRequestTest interface:
8847 void SetUpFactory() override {
8848 // Add FTP support to the default URLRequestContext.
8849 job_factory_impl_->SetProtocolHandler(
8850 "ftp", new FtpProtocolHandler(&ftp_transaction_factory_));
8851 }
8852
8853 std::string GetTestFileContents() {
8854 base::FilePath path;
8855 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
8856 path = path.Append(kTestFilePath);
8857 path = path.AppendASCII(kFtpTestFile);
8858 std::string contents;
8859 EXPECT_TRUE(base::ReadFileToString(path, &contents));
8860 return contents;
[email protected]95409e12010-08-17 20:07:118861 }
8862
[email protected]b89ca032009-08-31 21:41:318863 protected:
mmenke9f2ec60c2015-06-01 20:59:478864 MockHostResolver host_resolver_;
8865 FtpNetworkLayer ftp_transaction_factory_;
8866
[email protected]ce7d0cbc2013-05-03 18:57:228867 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:318868};
8869
[email protected]d2a133182012-08-05 16:44:088870// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:098871TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:088872 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:088873
8874 TestDelegate d;
8875 {
davidben151423e2015-03-23 18:48:368876 scoped_ptr<URLRequest> r(
8877 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198878 r->Start();
8879 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:088880
[email protected]255620da2013-08-19 13:14:298881 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:088882
[email protected]f7022f32014-08-21 16:32:198883 EXPECT_FALSE(r->is_pending());
8884 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8885 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:088886 }
8887}
8888
mmenke9f2ec60c2015-06-01 20:59:478889TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:118890 ASSERT_TRUE(test_server_.Start());
8891
[email protected]a25e90e2009-09-09 17:05:378892 TestDelegate d;
8893 {
[email protected]f7022f32014-08-21 16:32:198894 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368895 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198896 r->Start();
8897 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378898
[email protected]255620da2013-08-19 13:14:298899 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:378900
[email protected]f7022f32014-08-21 16:32:198901 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378902 EXPECT_EQ(1, d.response_started_count());
8903 EXPECT_FALSE(d.received_data_before_response());
8904 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:198905 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198906 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198907 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198908 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:378909 }
8910}
8911
mmenke9f2ec60c2015-06-01 20:59:478912TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:118913 ASSERT_TRUE(test_server_.Start());
8914
[email protected]dd265012009-01-08 20:45:278915 TestDelegate d;
8916 {
[email protected]f7022f32014-08-21 16:32:198917 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:478918 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198919 r->Start();
8920 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278921
[email protected]255620da2013-08-19 13:14:298922 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278923
[email protected]f7022f32014-08-21 16:32:198924 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278925 EXPECT_EQ(1, d.response_started_count());
8926 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:478927 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:198928 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198929 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198930 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198931 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278932 }
8933}
8934
mmenke9f2ec60c2015-06-01 20:59:478935TEST_F(URLRequestTestFTP, FTPGetTest) {
[email protected]95409e12010-08-17 20:07:118936 ASSERT_TRUE(test_server_.Start());
8937
[email protected]dd265012009-01-08 20:45:278938 TestDelegate d;
8939 {
mmenke9f2ec60c2015-06-01 20:59:478940 scoped_ptr<URLRequest> r(
8941 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
8942 kFtpTestFile, "chrome", "chrome"),
8943 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198944 r->Start();
8945 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278946
[email protected]255620da2013-08-19 13:14:298947 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278948
[email protected]f7022f32014-08-21 16:32:198949 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:478950 EXPECT_EQ(1, d.response_started_count());
8951 EXPECT_FALSE(d.received_data_before_response());
8952 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:198953 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198954 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198955 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198956 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:258957
8958 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198959 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258960 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:278961 }
8962}
8963
mmenke9f2ec60c2015-06-01 20:59:478964TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:118965 ASSERT_TRUE(test_server_.Start());
8966
[email protected]dd265012009-01-08 20:45:278967 TestDelegate d;
8968 {
[email protected]f7022f32014-08-21 16:32:198969 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:478970 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:198971 "wrong_password"),
davidben151423e2015-03-23 18:48:368972 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198973 r->Start();
8974 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278975
[email protected]255620da2013-08-19 13:14:298976 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278977
[email protected]f7022f32014-08-21 16:32:198978 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278979 EXPECT_EQ(1, d.response_started_count());
8980 EXPECT_FALSE(d.received_data_before_response());
8981 EXPECT_EQ(d.bytes_received(), 0);
8982 }
8983}
8984
mmenke9f2ec60c2015-06-01 20:59:478985TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:118986 ASSERT_TRUE(test_server_.Start());
8987
[email protected]8b8a197d2009-08-26 15:57:588988 TestDelegate d;
8989 // Set correct login credentials. The delegate will be asked for them when
8990 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588991 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:588992 {
[email protected]f7022f32014-08-21 16:32:198993 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:478994 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:198995 "wrong_password"),
davidben151423e2015-03-23 18:48:368996 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198997 r->Start();
8998 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588999
[email protected]255620da2013-08-19 13:14:299000 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589001
[email protected]f7022f32014-08-21 16:32:199002 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589003 EXPECT_EQ(1, d.response_started_count());
9004 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479005 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589006 }
9007}
9008
mmenke9f2ec60c2015-06-01 20:59:479009TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:119010 ASSERT_TRUE(test_server_.Start());
9011
[email protected]dd265012009-01-08 20:45:279012 TestDelegate d;
9013 {
mmenke9f2ec60c2015-06-01 20:59:479014 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9015 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9016 "chrome"),
9017 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199018 r->Start();
9019 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279020
[email protected]255620da2013-08-19 13:14:299021 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279022
[email protected]f7022f32014-08-21 16:32:199023 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279024 EXPECT_EQ(1, d.response_started_count());
9025 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479026 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279027 }
9028}
[email protected]8b8a197d2009-08-26 15:57:589029
mmenke9f2ec60c2015-06-01 20:59:479030TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:119031 ASSERT_TRUE(test_server_.Start());
9032
[email protected]8b8a197d2009-08-26 15:57:589033 TestDelegate d;
9034 // Set correct login credentials. The delegate will be asked for them when
9035 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589036 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589037 {
mmenke9f2ec60c2015-06-01 20:59:479038 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9039 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9040 "chrome"),
9041 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199042 r->Start();
9043 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589044
[email protected]255620da2013-08-19 13:14:299045 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589046
[email protected]f7022f32014-08-21 16:32:199047 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589048 EXPECT_EQ(1, d.response_started_count());
9049 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479050 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589051 }
9052}
[email protected]60a3df52009-09-22 16:13:249053
mmenke9f2ec60c2015-06-01 20:59:479054TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:119055 ASSERT_TRUE(test_server_.Start());
9056
[email protected]60a3df52009-09-22 16:13:249057 scoped_ptr<TestDelegate> d(new TestDelegate);
9058 {
9059 // Pass correct login identity in the URL.
mmenke9f2ec60c2015-06-01 20:59:479060 scoped_ptr<URLRequest> r(
9061 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9062 kFtpTestFile, "chrome", "chrome"),
9063 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199064 r->Start();
9065 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249066
[email protected]255620da2013-08-19 13:14:299067 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249068
[email protected]f7022f32014-08-21 16:32:199069 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249070 EXPECT_EQ(1, d->response_started_count());
9071 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479072 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249073 }
9074
9075 d.reset(new TestDelegate);
9076 {
9077 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199078 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479079 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199080 r->Start();
9081 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249082
[email protected]255620da2013-08-19 13:14:299083 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249084
[email protected]f7022f32014-08-21 16:32:199085 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249086 EXPECT_EQ(1, d->response_started_count());
9087 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479088 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249089 }
9090}
9091
mmenke9f2ec60c2015-06-01 20:59:479092TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:119093 ASSERT_TRUE(test_server_.Start());
9094
[email protected]60a3df52009-09-22 16:13:249095 scoped_ptr<TestDelegate> d(new TestDelegate);
9096 // Set correct login credentials. The delegate will be asked for them when
9097 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589098 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249099 {
[email protected]f7022f32014-08-21 16:32:199100 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479101 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199102 "wrong_password"),
davidben151423e2015-03-23 18:48:369103 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199104 r->Start();
9105 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249106
[email protected]255620da2013-08-19 13:14:299107 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249108
[email protected]f7022f32014-08-21 16:32:199109 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249110 EXPECT_EQ(1, d->response_started_count());
9111 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479112 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249113 }
9114
9115 // Use a new delegate without explicit credentials. The cached ones should be
9116 // used.
9117 d.reset(new TestDelegate);
9118 {
9119 // Don't pass wrong credentials in the URL, they would override valid cached
9120 // ones.
[email protected]f7022f32014-08-21 16:32:199121 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479122 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199123 r->Start();
9124 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249125
[email protected]255620da2013-08-19 13:14:299126 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249127
[email protected]f7022f32014-08-21 16:32:199128 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249129 EXPECT_EQ(1, d->response_started_count());
9130 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479131 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249132 }
9133}
[email protected]316c1e5e2012-09-12 15:17:449134#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519135
ttuttlec0c828492015-05-15 01:25:559136TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9137 TestDelegate d;
9138 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9139 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9140 d.set_quit_on_network_start(true);
9141
9142 EXPECT_FALSE(req->response_info().network_accessed);
9143
9144 req->Start();
9145 base::RunLoop().Run();
9146
9147 EXPECT_EQ(1, d.received_before_network_start_count());
9148 EXPECT_EQ(0, d.response_started_count());
9149 EXPECT_FALSE(req->response_info().network_accessed);
9150
9151 req->ResumeNetworkStart();
9152 base::RunLoop().Run();
9153}
9154
9155TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9156 TestDelegate d;
9157 scoped_ptr<URLRequest> req(
9158 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9159
9160 EXPECT_FALSE(req->response_info().network_accessed);
9161
9162 req->Start();
9163 base::RunLoop().Run();
9164
9165 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9166 EXPECT_FALSE(req->response_info().network_accessed);
9167}
9168
9169TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9170 MockHostResolver host_resolver;
9171 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9172 TestURLRequestContext context(true);
9173 context.set_network_delegate(&network_delegate);
9174 context.set_host_resolver(&host_resolver);
9175 host_resolver.rules()->AddSimulatedFailure("*");
9176 context.Init();
9177
9178 TestDelegate d;
9179 scoped_ptr<URLRequest> req(context.CreateRequest(
9180 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9181
9182 EXPECT_FALSE(req->response_info().network_accessed);
9183
9184 req->Start();
9185 base::RunLoop().Run();
9186 EXPECT_TRUE(req->response_info().network_accessed);
9187}
9188
[email protected]7461a402011-03-24 23:19:519189} // namespace net