blob: 0640dd41bb9e73b46be2009bb968b0d5f221090d [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.
tbansalb177b5392015-06-25 11:13:024080 std::map<std::string, std::string> variation_params;
4081 NetworkQualityEstimator estimator(variation_params, true, true);
tbansalea2fb8c2015-05-22 22:23:004082
4083 TestDelegate d;
4084 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4085 TestURLRequestContext context(true);
4086 context.set_network_quality_estimator(&estimator);
4087 context.set_network_delegate(&network_delegate);
4088 context.Init();
4089
tbansalafc2c1cb2015-06-15 23:58:594090 std::string url = "echo.html";
tbansalea2fb8c2015-05-22 22:23:004091
4092 scoped_ptr<URLRequest> r(
4093 context.CreateRequest(test_server_.GetURL(url), DEFAULT_PRIORITY, &d));
tbansalea2fb8c2015-05-22 22:23:004094 r->Start();
4095
4096 base::RunLoop().Run();
4097
4098 NetworkQuality network_quality =
tbansal6f840fc52015-06-13 03:30:344099 context.network_quality_estimator()->GetPeakEstimate();
tbansalafc2c1cb2015-06-15 23:58:594100 EXPECT_GE(network_quality.rtt(), base::TimeDelta());
4101 EXPECT_LT(network_quality.rtt(), base::TimeDelta::Max());
tbansal6f840fc52015-06-13 03:30:344102 EXPECT_GT(network_quality.downstream_throughput_kbps(), 0);
tbansalea2fb8c2015-05-22 22:23:004103
4104 // Verify that histograms are not populated. They should populate only when
4105 // there is a change in ConnectionType.
4106 base::HistogramTester histogram_tester;
4107 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 0);
4108 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 0);
4109
4110 NetworkChangeNotifier::NotifyObserversOfConnectionTypeChangeForTests(
4111 NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI);
4112 base::MessageLoop::current()->RunUntilIdle();
4113 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 1);
4114 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 1);
4115}
4116
[email protected]58e32bb2013-01-21 18:23:254117TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
4118 ASSERT_TRUE(test_server_.Start());
4119
[email protected]007b3f82013-04-09 08:46:454120 GURL destination_url = test_server_.GetURL(std::string());
4121 GURL original_url =
4122 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254123 TestDelegate d;
davidben151423e2015-03-23 18:48:364124 scoped_ptr<URLRequest> req(
4125 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194126 req->Start();
[email protected]255620da2013-08-19 13:14:294127 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254128
4129 EXPECT_EQ(1, d.response_started_count());
4130 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194131 EXPECT_EQ(destination_url, req->url());
4132 EXPECT_EQ(original_url, req->original_url());
4133 ASSERT_EQ(2U, req->url_chain().size());
4134 EXPECT_EQ(original_url, req->url_chain()[0]);
4135 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254136
4137 LoadTimingInfo load_timing_info_before_redirect;
4138 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4139 &load_timing_info_before_redirect));
4140 TestLoadTimingNotReused(load_timing_info_before_redirect,
4141 CONNECT_TIMING_HAS_DNS_TIMES);
4142
4143 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194144 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254145 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4146
4147 // Check that a new socket was used on redirect, since the server does not
4148 // supposed keep-alive sockets, and that the times before the redirect are
4149 // before the ones recorded for the second request.
4150 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4151 load_timing_info.socket_log_id);
4152 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4153 load_timing_info.connect_timing.connect_start);
4154}
4155
[email protected]8f1ac082011-04-19 21:14:134156TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
4157 ASSERT_TRUE(test_server_.Start());
4158
[email protected]007b3f82013-04-09 08:46:454159 GURL destination_url = test_server_.GetURL(std::string());
4160 GURL middle_redirect_url =
4161 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:134162 GURL original_url = test_server_.GetURL(
4163 "server-redirect?" + middle_redirect_url.spec());
4164 TestDelegate d;
davidben151423e2015-03-23 18:48:364165 scoped_ptr<URLRequest> req(
4166 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194167 req->Start();
[email protected]255620da2013-08-19 13:14:294168 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134169
4170 EXPECT_EQ(1, d.response_started_count());
4171 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194172 EXPECT_EQ(destination_url, req->url());
4173 EXPECT_EQ(original_url, req->original_url());
4174 ASSERT_EQ(3U, req->url_chain().size());
4175 EXPECT_EQ(original_url, req->url_chain()[0]);
4176 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4177 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134178}
4179
[email protected]abe1c4a2013-10-25 19:28:514180// First and second pieces of information logged by delegates to URLRequests.
4181const char kFirstDelegateInfo[] = "Wonderful delegate";
4182const char kSecondDelegateInfo[] = "Exciting delegate";
4183
4184// Logs delegate information to a URLRequest. The first string is logged
4185// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4186// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4187// another asynchronous call is used to clear the delegate information
4188// before calling a callback. The object then deletes itself.
4189class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4190 public:
4191 typedef base::Callback<void()> Callback;
4192
4193 // Each time delegate information is added to the URLRequest, the resulting
4194 // load state is checked. The expected load state after each request is
4195 // passed in as an argument.
4196 static void Run(URLRequest* url_request,
4197 LoadState expected_first_load_state,
4198 LoadState expected_second_load_state,
4199 LoadState expected_third_load_state,
4200 const Callback& callback) {
4201 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4202 url_request,
4203 expected_first_load_state,
4204 expected_second_load_state,
4205 expected_third_load_state,
4206 callback);
4207 logger->Start();
4208 }
4209
4210 // Checks that the log entries, starting with log_position, contain the
4211 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4212 // recorded. Returns the index of entry after the expected number of
4213 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464214 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514215 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514216 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4217 if (log_position + 3 >= entries.size()) {
4218 ADD_FAILURE() << "Not enough log entries";
4219 return entries.size();
4220 }
4221 std::string delegate_info;
4222 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4223 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4224 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4225 &delegate_info));
4226 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4227
4228 ++log_position;
4229 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4230 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4231
4232 ++log_position;
4233 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4234 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4235 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4236 &delegate_info));
4237 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4238
4239 ++log_position;
4240 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4241 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4242
4243 return log_position + 1;
4244 }
4245
[email protected]1826a402014-01-08 15:40:484246 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4247 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464248 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4249 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484250 log_position =
4251 ExpectLogContainsSomewhereAfter(entries,
4252 log_position,
4253 NetLog::TYPE_URL_REQUEST_DELEGATE,
4254 NetLog::PHASE_BEGIN);
4255 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4256 entries[log_position + 1].type);
4257 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4258 return log_position + 1;
4259 }
4260
[email protected]abe1c4a2013-10-25 19:28:514261 private:
4262 friend class base::RefCounted<AsyncDelegateLogger>;
4263
4264 AsyncDelegateLogger(URLRequest* url_request,
4265 LoadState expected_first_load_state,
4266 LoadState expected_second_load_state,
4267 LoadState expected_third_load_state,
4268 const Callback& callback)
4269 : url_request_(url_request),
4270 expected_first_load_state_(expected_first_load_state),
4271 expected_second_load_state_(expected_second_load_state),
4272 expected_third_load_state_(expected_third_load_state),
4273 callback_(callback) {
4274 }
4275
4276 ~AsyncDelegateLogger() {}
4277
4278 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534279 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514280 LoadStateWithParam load_state = url_request_->GetLoadState();
4281 EXPECT_EQ(expected_first_load_state_, load_state.state);
4282 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454283 base::ThreadTaskRunnerHandle::Get()->PostTask(
4284 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514285 }
4286
4287 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534288 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514289 LoadStateWithParam load_state = url_request_->GetLoadState();
4290 EXPECT_EQ(expected_second_load_state_, load_state.state);
4291 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4292 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4293 } else {
4294 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4295 }
skyostil4891b25b2015-06-11 11:43:454296 base::ThreadTaskRunnerHandle::Get()->PostTask(
4297 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514298 }
4299
4300 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534301 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514302 LoadStateWithParam load_state = url_request_->GetLoadState();
4303 EXPECT_EQ(expected_third_load_state_, load_state.state);
4304 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084305 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514306 callback_.Run();
4307 }
4308
4309 URLRequest* url_request_;
4310 const int expected_first_load_state_;
4311 const int expected_second_load_state_;
4312 const int expected_third_load_state_;
4313 const Callback callback_;
4314
4315 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4316};
4317
4318// NetworkDelegate that logs delegate information before a request is started,
4319// before headers are sent, when headers are read, and when auth information
4320// is requested. Uses AsyncDelegateLogger.
4321class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4322 public:
4323 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204324 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514325
4326 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204327 int OnBeforeURLRequest(URLRequest* request,
4328 const CompletionCallback& callback,
4329 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514330 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4331 return RunCallbackAsynchronously(request, callback);
4332 }
4333
dchengb03027d2014-10-21 12:00:204334 int OnBeforeSendHeaders(URLRequest* request,
4335 const CompletionCallback& callback,
4336 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514337 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4338 return RunCallbackAsynchronously(request, callback);
4339 }
4340
dchengb03027d2014-10-21 12:00:204341 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514342 URLRequest* request,
4343 const CompletionCallback& callback,
4344 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164345 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134346 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164347 TestNetworkDelegate::OnHeadersReceived(request,
4348 callback,
[email protected]abe1c4a2013-10-25 19:28:514349 original_response_headers,
[email protected]5f714132014-03-26 10:41:164350 override_response_headers,
4351 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514352 return RunCallbackAsynchronously(request, callback);
4353 }
4354
dchengb03027d2014-10-21 12:00:204355 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514356 URLRequest* request,
4357 const AuthChallengeInfo& auth_info,
4358 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134359 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514360 AsyncDelegateLogger::Run(
4361 request,
4362 LOAD_STATE_WAITING_FOR_DELEGATE,
4363 LOAD_STATE_WAITING_FOR_DELEGATE,
4364 LOAD_STATE_WAITING_FOR_DELEGATE,
4365 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4366 callback, credentials));
4367 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4368 }
4369
4370 private:
4371 static int RunCallbackAsynchronously(
4372 URLRequest* request,
4373 const CompletionCallback& callback) {
4374 AsyncDelegateLogger::Run(
4375 request,
4376 LOAD_STATE_WAITING_FOR_DELEGATE,
4377 LOAD_STATE_WAITING_FOR_DELEGATE,
4378 LOAD_STATE_WAITING_FOR_DELEGATE,
4379 base::Bind(callback, OK));
4380 return ERR_IO_PENDING;
4381 }
4382
4383 static void SetAuthAndResume(const AuthCallback& callback,
4384 AuthCredentials* credentials) {
4385 *credentials = AuthCredentials(kUser, kSecret);
4386 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4387 }
4388
4389 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4390};
4391
4392// URLRequest::Delegate that logs delegate information when the headers
4393// are received, when each read completes, and during redirects. Uses
4394// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4395//
4396// Inherits from TestDelegate to reuse the TestDelegate code to handle
4397// advancing to the next step in most cases, as well as cancellation.
4398class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4399 public:
4400 enum CancelStage {
4401 NO_CANCEL = 0,
4402 CANCEL_ON_RECEIVED_REDIRECT,
4403 CANCEL_ON_RESPONSE_STARTED,
4404 CANCEL_ON_READ_COMPLETED
4405 };
4406
4407 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4408 : cancel_stage_(cancel_stage) {
4409 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4410 set_cancel_in_received_redirect(true);
4411 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4412 set_cancel_in_response_started(true);
4413 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4414 set_cancel_in_received_data(true);
4415 }
dchengb03027d2014-10-21 12:00:204416 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514417
4418 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204419 void OnReceivedRedirect(URLRequest* request,
4420 const RedirectInfo& redirect_info,
4421 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514422 *defer_redirect = true;
4423 AsyncDelegateLogger::Run(
4424 request,
4425 LOAD_STATE_WAITING_FOR_DELEGATE,
4426 LOAD_STATE_WAITING_FOR_DELEGATE,
4427 LOAD_STATE_WAITING_FOR_DELEGATE,
4428 base::Bind(
4429 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594430 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514431 }
4432
dchengb03027d2014-10-21 12:00:204433 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514434 AsyncDelegateLogger::Run(
4435 request,
4436 LOAD_STATE_WAITING_FOR_DELEGATE,
4437 LOAD_STATE_WAITING_FOR_DELEGATE,
4438 LOAD_STATE_WAITING_FOR_DELEGATE,
4439 base::Bind(
4440 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4441 base::Unretained(this), request));
4442 }
4443
dchengb03027d2014-10-21 12:00:204444 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514445 AsyncDelegateLogger::Run(
4446 request,
4447 LOAD_STATE_IDLE,
4448 LOAD_STATE_IDLE,
4449 LOAD_STATE_IDLE,
4450 base::Bind(
4451 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4452 base::Unretained(this), request, bytes_read));
4453 }
4454
4455 private:
4456 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594457 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514458 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594459 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514460 // FollowDeferredRedirect should not be called after cancellation.
4461 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4462 return;
4463 if (!defer_redirect)
4464 request->FollowDeferredRedirect();
4465 }
4466
4467 void OnResponseStartedLoggingComplete(URLRequest* request) {
4468 // The parent class continues the request.
4469 TestDelegate::OnResponseStarted(request);
4470 }
4471
4472 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4473 // The parent class continues the request.
4474 TestDelegate::OnReadCompleted(request, bytes_read);
4475 }
4476
4477 const CancelStage cancel_stage_;
4478
4479 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4480};
4481
4482// Tests handling of delegate info before a request starts.
4483TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4484 ASSERT_TRUE(test_server_.Start());
4485
4486 TestDelegate request_delegate;
4487 TestURLRequestContext context(true);
4488 context.set_network_delegate(NULL);
4489 context.set_net_log(&net_log_);
4490 context.Init();
4491
4492 {
davidben151423e2015-03-23 18:48:364493 scoped_ptr<URLRequest> r(
4494 context.CreateRequest(test_server_.GetURL("empty.html"),
4495 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194496 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514497 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084498 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514499
4500 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194501 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514502 LOAD_STATE_WAITING_FOR_DELEGATE,
4503 LOAD_STATE_WAITING_FOR_DELEGATE,
4504 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194505 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514506
4507 base::RunLoop().Run();
4508
[email protected]f7022f32014-08-21 16:32:194509 EXPECT_EQ(200, r->GetResponseCode());
4510 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514511 }
4512
mmenke43758e62015-05-04 21:09:464513 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514514 net_log_.GetEntries(&entries);
4515 size_t log_position = ExpectLogContainsSomewhereAfter(
4516 entries,
4517 0,
4518 NetLog::TYPE_DELEGATE_INFO,
4519 NetLog::PHASE_BEGIN);
4520
4521 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4522
4523 // Nothing else should add any delegate info to the request.
4524 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4525 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4526}
4527
4528// Tests handling of delegate info from a network delegate.
4529TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4530 ASSERT_TRUE(test_server_.Start());
4531
4532 TestDelegate request_delegate;
4533 AsyncLoggingNetworkDelegate network_delegate;
4534 TestURLRequestContext context(true);
4535 context.set_network_delegate(&network_delegate);
4536 context.set_net_log(&net_log_);
4537 context.Init();
4538
4539 {
davidben151423e2015-03-23 18:48:364540 scoped_ptr<URLRequest> r(
4541 context.CreateRequest(test_server_.GetURL("simple.html"),
4542 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194543 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514544 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084545 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514546
[email protected]f7022f32014-08-21 16:32:194547 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514548 base::RunLoop().Run();
4549
[email protected]f7022f32014-08-21 16:32:194550 EXPECT_EQ(200, r->GetResponseCode());
4551 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514552 EXPECT_EQ(1, network_delegate.created_requests());
4553 EXPECT_EQ(0, network_delegate.destroyed_requests());
4554 }
4555 EXPECT_EQ(1, network_delegate.destroyed_requests());
4556
4557 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464558 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514559 net_log_.GetEntries(&entries);
4560 for (size_t i = 0; i < 3; ++i) {
4561 log_position = ExpectLogContainsSomewhereAfter(
4562 entries,
4563 log_position + 1,
4564 NetLog::TYPE_URL_REQUEST_DELEGATE,
4565 NetLog::PHASE_BEGIN);
4566
4567 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4568 log_position + 1);
4569
4570 ASSERT_LT(log_position, entries.size());
4571 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4572 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484573
4574 if (i == 1) {
4575 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4576 entries, log_position + 1);
4577 }
[email protected]abe1c4a2013-10-25 19:28:514578 }
4579
4580 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4581 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4582}
4583
4584// Tests handling of delegate info from a network delegate in the case of an
4585// HTTP redirect.
4586TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4587 ASSERT_TRUE(test_server_.Start());
4588
4589 TestDelegate request_delegate;
4590 AsyncLoggingNetworkDelegate network_delegate;
4591 TestURLRequestContext context(true);
4592 context.set_network_delegate(&network_delegate);
4593 context.set_net_log(&net_log_);
4594 context.Init();
4595
4596 {
[email protected]f7022f32014-08-21 16:32:194597 scoped_ptr<URLRequest> r(context.CreateRequest(
4598 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364599 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194600 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514601 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084602 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514603
[email protected]f7022f32014-08-21 16:32:194604 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514605 base::RunLoop().Run();
4606
[email protected]f7022f32014-08-21 16:32:194607 EXPECT_EQ(200, r->GetResponseCode());
4608 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514609 EXPECT_EQ(2, network_delegate.created_requests());
4610 EXPECT_EQ(0, network_delegate.destroyed_requests());
4611 }
4612 EXPECT_EQ(1, network_delegate.destroyed_requests());
4613
4614 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464615 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514616 net_log_.GetEntries(&entries);
4617 // The NetworkDelegate logged information in OnBeforeURLRequest,
4618 // OnBeforeSendHeaders, and OnHeadersReceived.
4619 for (size_t i = 0; i < 3; ++i) {
4620 log_position = ExpectLogContainsSomewhereAfter(
4621 entries,
4622 log_position + 1,
4623 NetLog::TYPE_URL_REQUEST_DELEGATE,
4624 NetLog::PHASE_BEGIN);
4625
4626 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4627 log_position + 1);
4628
4629 ASSERT_LT(log_position, entries.size());
4630 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4631 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484632
4633 if (i == 1) {
4634 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4635 entries, log_position + 1);
4636 }
[email protected]abe1c4a2013-10-25 19:28:514637 }
4638
4639 // The URLRequest::Delegate then gets informed about the redirect.
4640 log_position = ExpectLogContainsSomewhereAfter(
4641 entries,
4642 log_position + 1,
4643 NetLog::TYPE_URL_REQUEST_DELEGATE,
4644 NetLog::PHASE_BEGIN);
4645
4646 // The NetworkDelegate logged information in the same three events as before.
4647 for (size_t i = 0; i < 3; ++i) {
4648 log_position = ExpectLogContainsSomewhereAfter(
4649 entries,
4650 log_position + 1,
4651 NetLog::TYPE_URL_REQUEST_DELEGATE,
4652 NetLog::PHASE_BEGIN);
4653
4654 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4655 log_position + 1);
4656
4657 ASSERT_LT(log_position, entries.size());
4658 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4659 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4660 }
4661
4662 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4663 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4664}
4665
4666// Tests handling of delegate info from a network delegate in the case of HTTP
4667// AUTH.
4668TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4669 ASSERT_TRUE(test_server_.Start());
4670
4671 TestDelegate request_delegate;
4672 AsyncLoggingNetworkDelegate network_delegate;
4673 TestURLRequestContext context(true);
4674 context.set_network_delegate(&network_delegate);
4675 context.set_net_log(&net_log_);
4676 context.Init();
4677
4678 {
davidben151423e2015-03-23 18:48:364679 scoped_ptr<URLRequest> r(
4680 context.CreateRequest(test_server_.GetURL("auth-basic"),
4681 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194682 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514683 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084684 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514685
[email protected]f7022f32014-08-21 16:32:194686 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514687 base::RunLoop().Run();
4688
[email protected]f7022f32014-08-21 16:32:194689 EXPECT_EQ(200, r->GetResponseCode());
4690 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514691 EXPECT_EQ(1, network_delegate.created_requests());
4692 EXPECT_EQ(0, network_delegate.destroyed_requests());
4693 }
4694 EXPECT_EQ(1, network_delegate.destroyed_requests());
4695
4696 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464697 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514698 net_log_.GetEntries(&entries);
4699 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4700 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4701 // OnBeforeURLRequest and OnBeforeSendHeaders.
4702 for (size_t i = 0; i < 6; ++i) {
4703 log_position = ExpectLogContainsSomewhereAfter(
4704 entries,
4705 log_position + 1,
4706 NetLog::TYPE_URL_REQUEST_DELEGATE,
4707 NetLog::PHASE_BEGIN);
4708
4709 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4710 log_position + 1);
4711
4712 ASSERT_LT(log_position, entries.size());
4713 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4714 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484715
4716 if (i == 1) {
4717 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4718 entries, log_position + 1);
4719 }
[email protected]abe1c4a2013-10-25 19:28:514720 }
4721
4722 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4723 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4724}
4725
4726// Tests handling of delegate info from a URLRequest::Delegate.
4727TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4728 ASSERT_TRUE(test_server_.Start());
4729
4730 AsyncLoggingUrlRequestDelegate request_delegate(
4731 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4732 TestURLRequestContext context(true);
4733 context.set_network_delegate(NULL);
4734 context.set_net_log(&net_log_);
4735 context.Init();
4736
4737 {
4738 // A chunked response with delays between chunks is used to make sure that
4739 // attempts by the URLRequest delegate to log information while reading the
4740 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:484741 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:514742 // that it occurs.
[email protected]f7022f32014-08-21 16:32:194743 scoped_ptr<URLRequest> r(context.CreateRequest(
4744 test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364745 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194746 LoadStateWithParam load_state = r->GetLoadState();
4747 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514748 base::RunLoop().Run();
4749
[email protected]f7022f32014-08-21 16:32:194750 EXPECT_EQ(200, r->GetResponseCode());
4751 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514752 }
4753
mmenke43758e62015-05-04 21:09:464754 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514755 net_log_.GetEntries(&entries);
4756
[email protected]1826a402014-01-08 15:40:484757 size_t log_position = 0;
4758
4759 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4760 entries, log_position);
4761
[email protected]abe1c4a2013-10-25 19:28:514762 // The delegate info should only have been logged on header complete. Other
4763 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:484764 log_position =
4765 ExpectLogContainsSomewhereAfter(entries,
4766 log_position + 1,
4767 NetLog::TYPE_URL_REQUEST_DELEGATE,
4768 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:514769
4770 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4771 log_position + 1);
4772
4773 ASSERT_LT(log_position, entries.size());
4774 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4775 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4776
4777 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4778 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4779 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4780 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4781}
4782
4783// Tests handling of delegate info from a URLRequest::Delegate in the case of
4784// an HTTP redirect.
4785TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4786 ASSERT_TRUE(test_server_.Start());
4787
4788 AsyncLoggingUrlRequestDelegate request_delegate(
4789 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4790 TestURLRequestContext context(true);
4791 context.set_network_delegate(NULL);
4792 context.set_net_log(&net_log_);
4793 context.Init();
4794
4795 {
[email protected]f7022f32014-08-21 16:32:194796 scoped_ptr<URLRequest> r(context.CreateRequest(
4797 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364798 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194799 LoadStateWithParam load_state = r->GetLoadState();
4800 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514801 base::RunLoop().Run();
4802
[email protected]f7022f32014-08-21 16:32:194803 EXPECT_EQ(200, r->GetResponseCode());
4804 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514805 }
4806
mmenke43758e62015-05-04 21:09:464807 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514808 net_log_.GetEntries(&entries);
4809
4810 // Delegate info should only have been logged in OnReceivedRedirect and
4811 // OnResponseStarted.
4812 size_t log_position = 0;
4813 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484814 if (i == 0) {
4815 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4816 entries, log_position) + 1;
4817 }
4818
[email protected]abe1c4a2013-10-25 19:28:514819 log_position = ExpectLogContainsSomewhereAfter(
4820 entries,
4821 log_position,
4822 NetLog::TYPE_URL_REQUEST_DELEGATE,
4823 NetLog::PHASE_BEGIN);
4824
4825 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4826 log_position + 1);
4827
4828 ASSERT_LT(log_position, entries.size());
4829 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4830 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4831 }
4832
4833 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4834 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4835 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4836 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4837}
4838
4839// Tests handling of delegate info from a URLRequest::Delegate in the case of
4840// an HTTP redirect, with cancellation at various points.
4841TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4842 ASSERT_TRUE(test_server_.Start());
4843
4844 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4845 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4846 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4847 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4848 };
4849
4850 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4851 ++test_case) {
4852 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4853 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:514854 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:514855 context.set_network_delegate(NULL);
4856 context.set_net_log(&net_log);
4857 context.Init();
4858
4859 {
[email protected]f7022f32014-08-21 16:32:194860 scoped_ptr<URLRequest> r(context.CreateRequest(
4861 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364862 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194863 LoadStateWithParam load_state = r->GetLoadState();
4864 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514865 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194866 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514867 }
4868
mmenke43758e62015-05-04 21:09:464869 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514870 net_log.GetEntries(&entries);
4871
4872 // Delegate info is always logged in both OnReceivedRedirect and
4873 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4874 // OnResponseStarted delegate call is after cancellation, but logging is
4875 // still currently supported in that call.
4876 size_t log_position = 0;
4877 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484878 if (i == 0) {
4879 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4880 entries, log_position) + 1;
4881 }
4882
[email protected]abe1c4a2013-10-25 19:28:514883 log_position = ExpectLogContainsSomewhereAfter(
4884 entries,
4885 log_position,
4886 NetLog::TYPE_URL_REQUEST_DELEGATE,
4887 NetLog::PHASE_BEGIN);
4888
4889 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4890 log_position + 1);
4891
4892 ASSERT_LT(log_position, entries.size());
4893 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4894 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4895 }
4896
4897 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4898 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4899 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4900 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4901 }
4902}
4903
[email protected]847c0fa92012-11-06 16:37:424904namespace {
4905
4906const char kExtraHeader[] = "Allow-Snafu";
4907const char kExtraValue[] = "fubar";
4908
4909class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204910 void OnReceivedRedirect(URLRequest* request,
4911 const RedirectInfo& redirect_info,
4912 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594913 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:424914 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4915 }
4916};
4917
4918} // namespace
4919
4920TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4921 ASSERT_TRUE(test_server_.Start());
4922
4923 GURL destination_url = test_server_.GetURL(
4924 "echoheader?" + std::string(kExtraHeader));
4925 GURL original_url = test_server_.GetURL(
4926 "server-redirect?" + destination_url.spec());
4927 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:364928 scoped_ptr<URLRequest> req(
4929 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194930 req->Start();
[email protected]255620da2013-08-19 13:14:294931 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:424932
4933 std::string value;
[email protected]f7022f32014-08-21 16:32:194934 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:424935 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4936 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:194937 EXPECT_FALSE(req->is_pending());
4938 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:424939 EXPECT_EQ(kExtraValue, d.data_received());
4940}
4941
[email protected]251a1b92012-11-13 11:01:094942namespace {
4943
4944const char kExtraHeaderToRemove[] = "To-Be-Removed";
4945
4946class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204947 void OnReceivedRedirect(URLRequest* request,
4948 const RedirectInfo& redirect_info,
4949 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594950 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:094951 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4952 }
4953};
4954
4955} // namespace
4956
4957TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4958 ASSERT_TRUE(test_server_.Start());
4959
4960 GURL destination_url = test_server_.GetURL(
4961 "echoheader?" + std::string(kExtraHeaderToRemove));
4962 GURL original_url = test_server_.GetURL(
4963 "server-redirect?" + destination_url.spec());
4964 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:364965 scoped_ptr<URLRequest> req(
4966 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194967 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4968 req->Start();
[email protected]255620da2013-08-19 13:14:294969 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:094970
4971 std::string value;
[email protected]f7022f32014-08-21 16:32:194972 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:094973 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:194974 EXPECT_FALSE(req->is_pending());
4975 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:094976 EXPECT_EQ("None", d.data_received());
4977}
4978
[email protected]316c1e5e2012-09-12 15:17:444979TEST_F(URLRequestTestHTTP, CancelTest) {
4980 TestDelegate d;
4981 {
[email protected]f7022f32014-08-21 16:32:194982 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364983 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:444984
[email protected]f7022f32014-08-21 16:32:194985 r->Start();
4986 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444987
[email protected]f7022f32014-08-21 16:32:194988 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:444989
[email protected]255620da2013-08-19 13:14:294990 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444991
4992 // We expect to receive OnResponseStarted even though the request has been
4993 // cancelled.
4994 EXPECT_EQ(1, d.response_started_count());
4995 EXPECT_EQ(0, d.bytes_received());
4996 EXPECT_FALSE(d.received_data_before_response());
4997 }
4998}
4999
5000TEST_F(URLRequestTestHTTP, CancelTest2) {
5001 ASSERT_TRUE(test_server_.Start());
5002
5003 TestDelegate d;
5004 {
[email protected]f7022f32014-08-21 16:32:195005 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365006 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445007
5008 d.set_cancel_in_response_started(true);
5009
[email protected]f7022f32014-08-21 16:32:195010 r->Start();
5011 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445012
[email protected]255620da2013-08-19 13:14:295013 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445014
5015 EXPECT_EQ(1, d.response_started_count());
5016 EXPECT_EQ(0, d.bytes_received());
5017 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195018 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445019 }
5020}
5021
5022TEST_F(URLRequestTestHTTP, CancelTest3) {
5023 ASSERT_TRUE(test_server_.Start());
5024
5025 TestDelegate d;
5026 {
[email protected]f7022f32014-08-21 16:32:195027 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365028 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445029
5030 d.set_cancel_in_received_data(true);
5031
[email protected]f7022f32014-08-21 16:32:195032 r->Start();
5033 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445034
[email protected]255620da2013-08-19 13:14:295035 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445036
5037 EXPECT_EQ(1, d.response_started_count());
5038 // There is no guarantee about how much data was received
5039 // before the cancel was issued. It could have been 0 bytes,
5040 // or it could have been all the bytes.
5041 // EXPECT_EQ(0, d.bytes_received());
5042 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195043 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445044 }
5045}
5046
5047TEST_F(URLRequestTestHTTP, CancelTest4) {
5048 ASSERT_TRUE(test_server_.Start());
5049
5050 TestDelegate d;
5051 {
[email protected]f7022f32014-08-21 16:32:195052 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365053 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445054
[email protected]f7022f32014-08-21 16:32:195055 r->Start();
5056 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445057
5058 // The request will be implicitly canceled when it is destroyed. The
5059 // test delegate must not post a quit message when this happens because
5060 // this test doesn't actually have a message loop. The quit message would
5061 // get put on this thread's message queue and the next test would exit
5062 // early, causing problems.
5063 d.set_quit_on_complete(false);
5064 }
5065 // expect things to just cleanup properly.
5066
5067 // we won't actually get a received reponse here because we've never run the
5068 // message loop
5069 EXPECT_FALSE(d.received_data_before_response());
5070 EXPECT_EQ(0, d.bytes_received());
5071}
5072
5073TEST_F(URLRequestTestHTTP, CancelTest5) {
5074 ASSERT_TRUE(test_server_.Start());
5075
5076 // populate cache
5077 {
5078 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195079 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365080 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195081 r->Start();
[email protected]255620da2013-08-19 13:14:295082 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195083 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445084 }
5085
5086 // cancel read from cache (see bug 990242)
5087 {
5088 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195089 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365090 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195091 r->Start();
5092 r->Cancel();
[email protected]255620da2013-08-19 13:14:295093 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445094
[email protected]f7022f32014-08-21 16:32:195095 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445096 EXPECT_EQ(1, d.response_started_count());
5097 EXPECT_EQ(0, d.bytes_received());
5098 EXPECT_FALSE(d.received_data_before_response());
5099 }
5100}
5101
5102TEST_F(URLRequestTestHTTP, PostTest) {
5103 ASSERT_TRUE(test_server_.Start());
5104 HTTPUploadDataOperationTest("POST");
5105}
5106
5107TEST_F(URLRequestTestHTTP, PutTest) {
5108 ASSERT_TRUE(test_server_.Start());
5109 HTTPUploadDataOperationTest("PUT");
5110}
5111
5112TEST_F(URLRequestTestHTTP, PostEmptyTest) {
5113 ASSERT_TRUE(test_server_.Start());
5114
5115 TestDelegate d;
5116 {
[email protected]f7022f32014-08-21 16:32:195117 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365118 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195119 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445120
[email protected]f7022f32014-08-21 16:32:195121 r->Start();
5122 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445123
[email protected]255620da2013-08-19 13:14:295124 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445125
[email protected]329b68b2012-11-14 17:54:275126 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195127 << "request failed: " << r->status().status()
5128 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445129
5130 EXPECT_FALSE(d.received_data_before_response());
5131 EXPECT_TRUE(d.data_received().empty());
5132 }
5133}
5134
5135TEST_F(URLRequestTestHTTP, PostFileTest) {
5136 ASSERT_TRUE(test_server_.Start());
5137
5138 TestDelegate d;
5139 {
[email protected]f7022f32014-08-21 16:32:195140 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365141 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195142 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445143
[email protected]6cdfd7f2013-02-08 20:40:155144 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445145 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025146 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445147
[email protected]f288ef02012-12-15 20:28:285148 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445149
[email protected]6cdfd7f2013-02-08 20:40:155150 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445151 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475152 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445153 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:365154 element_readers.push_back(
skyostil4891b25b2015-06-11 11:43:455155 new UploadFileElementReader(base::ThreadTaskRunnerHandle::Get().get(),
5156 path, 0, kuint64max, base::Time()));
mmenkecbc2b712014-10-09 20:29:075157 r->set_upload(make_scoped_ptr<UploadDataStream>(
5158 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:445159
[email protected]f7022f32014-08-21 16:32:195160 r->Start();
5161 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445162
[email protected]255620da2013-08-19 13:14:295163 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445164
pkasting6b68a162014-12-01 22:10:295165 int64 size64 = 0;
5166 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5167 ASSERT_LE(size64, std::numeric_limits<int>::max());
5168 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175169 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445170
[email protected]7600d0b2013-12-08 21:43:305171 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445172
[email protected]329b68b2012-11-14 17:54:275173 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195174 << "request failed: " << r->status().status()
5175 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445176
5177 EXPECT_FALSE(d.received_data_before_response());
5178
[email protected]329b68b2012-11-14 17:54:275179 EXPECT_EQ(size, d.bytes_received());
5180 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445181 }
5182}
5183
[email protected]999dd8c2013-11-12 06:45:545184TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
5185 ASSERT_TRUE(test_server_.Start());
5186
5187 TestDelegate d;
5188 {
[email protected]f7022f32014-08-21 16:32:195189 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365190 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195191 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545192
5193 ScopedVector<UploadElementReader> element_readers;
5194
5195 element_readers.push_back(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455196 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545197 base::FilePath(FILE_PATH_LITERAL(
5198 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
skyostil4891b25b2015-06-11 11:43:455199 0, kuint64max, base::Time()));
mmenkecbc2b712014-10-09 20:29:075200 r->set_upload(make_scoped_ptr<UploadDataStream>(
5201 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]999dd8c2013-11-12 06:45:545202
[email protected]f7022f32014-08-21 16:32:195203 r->Start();
5204 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545205
5206 base::RunLoop().Run();
5207
[email protected]999dd8c2013-11-12 06:45:545208 EXPECT_TRUE(d.request_failed());
5209 EXPECT_FALSE(d.received_data_before_response());
5210 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195211 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5212 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545213 }
5214}
5215
[email protected]316c1e5e2012-09-12 15:17:445216TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5217 ASSERT_TRUE(test_server_.Start());
5218
5219 TestDelegate d;
5220 {
[email protected]f7022f32014-08-21 16:32:195221 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365222 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195223 r->EnableChunkedUpload();
5224 r->set_method("POST");
5225 AddChunksToUpload(r.get());
5226 r->Start();
5227 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445228
[email protected]255620da2013-08-19 13:14:295229 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445230
[email protected]f7022f32014-08-21 16:32:195231 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445232 }
5233}
5234
[email protected]329b68b2012-11-14 17:54:275235TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5236 ASSERT_TRUE(test_server_.Start());
5237
5238 TestDelegate d;
5239 {
[email protected]f7022f32014-08-21 16:32:195240 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365241 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195242 r->EnableChunkedUpload();
5243 r->set_method("POST");
5244 r->Start();
5245 EXPECT_TRUE(r->is_pending());
5246 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295247 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275248
[email protected]f7022f32014-08-21 16:32:195249 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275250 }
5251}
5252
[email protected]316c1e5e2012-09-12 15:17:445253TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5254 ASSERT_TRUE(test_server_.Start());
5255
5256 TestDelegate d;
5257 {
[email protected]f7022f32014-08-21 16:32:195258 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365259 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195260 r->EnableChunkedUpload();
5261 r->set_method("POST");
5262 r->Start();
5263 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445264
[email protected]255620da2013-08-19 13:14:295265 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195266 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295267 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445268
[email protected]f7022f32014-08-21 16:32:195269 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445270 }
5271}
5272
5273TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5274 ASSERT_TRUE(test_server_.Start());
5275
5276 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195277 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365278 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195279 req->Start();
[email protected]255620da2013-08-19 13:14:295280 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445281
[email protected]f7022f32014-08-21 16:32:195282 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445283
5284 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195285 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445286
5287 std::string header;
5288 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5289 EXPECT_EQ("private", header);
5290
5291 header.clear();
5292 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5293 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5294
5295 // The response has two "X-Multiple-Entries" headers.
5296 // This verfies our output has them concatenated together.
5297 header.clear();
5298 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5299 EXPECT_EQ("a, b", header);
5300}
5301
[email protected]242d8562012-10-30 21:20:465302TEST_F(URLRequestTestHTTP, ProcessSTS) {
estarka5da76702015-04-09 04:00:165303 SpawnedTestServer::SSLOptions ssl_options(
5304 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475305 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5306 ssl_options,
5307 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465308 ASSERT_TRUE(https_test_server.Start());
5309
estarka5da76702015-04-09 04:00:165310 std::string test_server_hostname = https_test_server.GetURL("").host();
5311
[email protected]242d8562012-10-30 21:20:465312 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195313 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365314 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5315 &d));
[email protected]f7022f32014-08-21 16:32:195316 request->Start();
[email protected]255620da2013-08-19 13:14:295317 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465318
5319 TransportSecurityState* security_state =
5320 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405321 TransportSecurityState::STSState sts_state;
5322 TransportSecurityState::PKPState pkp_state;
5323 EXPECT_TRUE(
5324 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5325 EXPECT_FALSE(
5326 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5327 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5328 sts_state.upgrade_mode);
5329 EXPECT_TRUE(sts_state.include_subdomains);
5330 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275331#if defined(OS_ANDROID)
5332 // Android's CertVerifyProc does not (yet) handle pins.
5333#else
martijnc0d6b622015-06-30 19:14:405334 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
[email protected]37fd55fb2013-06-29 13:13:275335#endif
5336}
5337
estarka5da76702015-04-09 04:00:165338TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
mmenke9f2ec60c2015-06-01 20:59:475339 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5340 SpawnedTestServer::SSLOptions(),
5341 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165342 ASSERT_TRUE(https_test_server.Start());
5343 // Make sure this test fails if the test server is changed to not
5344 // listen on an IP by default.
5345 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5346 std::string test_server_hostname = https_test_server.GetURL("").host();
5347
5348 TestDelegate d;
5349 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5350 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5351 &d));
5352 request->Start();
5353 base::RunLoop().Run();
5354
5355 TransportSecurityState* security_state =
5356 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405357 TransportSecurityState::STSState sts_state;
5358 EXPECT_FALSE(
5359 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165360}
5361
[email protected]37fd55fb2013-06-29 13:13:275362// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5363// reject HPKP headers, and a test setting only HPKP headers will fail (no
martijnc0d6b622015-06-30 19:14:405364// PKPState present because header rejected).
[email protected]37fd55fb2013-06-29 13:13:275365#if defined(OS_ANDROID)
5366#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5367#else
5368#define MAYBE_ProcessPKP ProcessPKP
5369#endif
5370
5371// Tests that enabling HPKP on a domain does not affect the HSTS
5372// validity/expiration.
5373TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estarka5da76702015-04-09 04:00:165374 SpawnedTestServer::SSLOptions ssl_options(
5375 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475376 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5377 ssl_options,
5378 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275379 ASSERT_TRUE(https_test_server.Start());
5380
estarka5da76702015-04-09 04:00:165381 std::string test_server_hostname = https_test_server.GetURL("").host();
5382
[email protected]37fd55fb2013-06-29 13:13:275383 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195384 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365385 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5386 &d));
[email protected]f7022f32014-08-21 16:32:195387 request->Start();
[email protected]255620da2013-08-19 13:14:295388 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275389
5390 TransportSecurityState* security_state =
5391 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405392 TransportSecurityState::STSState sts_state;
5393 TransportSecurityState::PKPState pkp_state;
5394 EXPECT_FALSE(
5395 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5396 EXPECT_TRUE(
5397 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5398 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
5399 sts_state.upgrade_mode);
5400 EXPECT_FALSE(sts_state.include_subdomains);
5401 EXPECT_FALSE(pkp_state.include_subdomains);
5402 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
5403 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:465404}
5405
estarka5da76702015-04-09 04:00:165406TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
mmenke9f2ec60c2015-06-01 20:59:475407 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5408 SpawnedTestServer::SSLOptions(),
5409 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165410 ASSERT_TRUE(https_test_server.Start());
5411 // Make sure this test fails if the test server is changed to not
5412 // listen on an IP by default.
5413 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5414 std::string test_server_hostname = https_test_server.GetURL("").host();
5415
5416 TestDelegate d;
5417 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5418 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5419 &d));
5420 request->Start();
5421 base::RunLoop().Run();
5422
5423 TransportSecurityState* security_state =
5424 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405425 TransportSecurityState::PKPState pkp_state;
5426 EXPECT_FALSE(
5427 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:165428}
5429
[email protected]242d8562012-10-30 21:20:465430TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
estarka5da76702015-04-09 04:00:165431 SpawnedTestServer::SSLOptions ssl_options(
5432 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475433 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5434 ssl_options,
5435 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465436 ASSERT_TRUE(https_test_server.Start());
5437
estarka5da76702015-04-09 04:00:165438 std::string test_server_hostname = https_test_server.GetURL("").host();
5439
[email protected]242d8562012-10-30 21:20:465440 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195441 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]242d8562012-10-30 21:20:465442 https_test_server.GetURL("files/hsts-multiple-headers.html"),
davidben151423e2015-03-23 18:48:365443 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195444 request->Start();
[email protected]255620da2013-08-19 13:14:295445 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465446
5447 // We should have set parameters from the first header, not the second.
5448 TransportSecurityState* security_state =
5449 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405450 TransportSecurityState::STSState sts_state;
5451 EXPECT_TRUE(
5452 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5453 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5454 sts_state.upgrade_mode);
5455 EXPECT_FALSE(sts_state.include_subdomains);
5456 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:465457}
5458
[email protected]9f972ec2013-04-10 20:24:365459TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
estarka5da76702015-04-09 04:00:165460 SpawnedTestServer::SSLOptions ssl_options(
5461 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475462 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5463 ssl_options,
5464 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:365465 ASSERT_TRUE(https_test_server.Start());
5466
estarka5da76702015-04-09 04:00:165467 std::string test_server_hostname = https_test_server.GetURL("").host();
5468
[email protected]9f972ec2013-04-10 20:24:365469 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195470 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]9f972ec2013-04-10 20:24:365471 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
davidben151423e2015-03-23 18:48:365472 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195473 request->Start();
[email protected]255620da2013-08-19 13:14:295474 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365475
5476 // We should have set parameters from the first header, not the second.
5477 TransportSecurityState* security_state =
5478 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405479 TransportSecurityState::STSState sts_state;
5480 TransportSecurityState::PKPState pkp_state;
5481 EXPECT_TRUE(
5482 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5483 EXPECT_TRUE(
5484 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5485 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5486 sts_state.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
martijnc0d6b622015-06-30 19:14:405490 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
[email protected]9f972ec2013-04-10 20:24:365491#endif
martijnc0d6b622015-06-30 19:14:405492 EXPECT_NE(sts_state.expiry, pkp_state.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.
martijnc0d6b622015-06-30 19:14:405496 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:055497 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:405498 EXPECT_FALSE(pkp_state.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();
martijnc0d6b622015-06-30 19:14:405522 TransportSecurityState::STSState sts_state;
5523 TransportSecurityState::PKPState pkp_state;
5524 EXPECT_TRUE(
5525 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5526 EXPECT_TRUE(
5527 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5528 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5529 sts_state.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:275530#if defined(OS_ANDROID)
5531 // Android's CertVerifyProc does not (yet) handle pins.
5532#else
martijnc0d6b622015-06-30 19:14:405533 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
[email protected]37fd55fb2013-06-29 13:13:275534#endif
martijnc0d6b622015-06-30 19:14:405535 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:275536
martijnc0d6b622015-06-30 19:14:405537 EXPECT_TRUE(sts_state.include_subdomains);
5538 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275539}
5540
[email protected]316c1e5e2012-09-12 15:17:445541TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5542 ASSERT_TRUE(test_server_.Start());
5543
5544 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195545 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5546 test_server_.GetURL("files/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:365547 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195548 req->Start();
[email protected]255620da2013-08-19 13:14:295549 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445550
5551 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:195552 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:445553 EXPECT_EQ("text/html", mime_type);
5554
5555 std::string charset;
[email protected]f7022f32014-08-21 16:32:195556 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:445557 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:195558 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445559}
5560
[email protected]02494ec2014-05-07 15:05:295561TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:345562 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:345563 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:345564 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025565 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345566
5567 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505568 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345569}
5570
[email protected]02494ec2014-05-07 15:05:295571#if !defined(DISABLE_FILE_SUPPORT)
5572TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5573 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5574 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:455575 FileProtocolHandler file_protocol_handler(
5576 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:295577 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5578
5579 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505580 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:295581}
5582
[email protected]588614c22013-08-16 00:09:025583TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445584 ASSERT_TRUE(test_server_.Start());
5585
5586 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195587 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365588 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY,
5589 &d));
[email protected]f7022f32014-08-21 16:32:195590 req->Start();
[email protected]255620da2013-08-19 13:14:295591 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445592
[email protected]f7022f32014-08-21 16:32:195593 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5594 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445595}
[email protected]02494ec2014-05-07 15:05:295596#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:445597
[email protected]588614c22013-08-16 00:09:025598TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5599 ASSERT_TRUE(test_server_.Start());
5600
5601 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195602 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365603 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY,
5604 &d));
[email protected]f7022f32014-08-21 16:32:195605 req->Start();
[email protected]588614c22013-08-16 00:09:025606 base::MessageLoop::current()->Run();
5607
[email protected]f7022f32014-08-21 16:32:195608 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5609 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:025610}
5611
[email protected]316c1e5e2012-09-12 15:17:445612TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5613 ASSERT_TRUE(test_server_.Start());
5614
5615 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195616 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5617 test_server_.GetURL("files/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:365618 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195619 req->Start();
[email protected]255620da2013-08-19 13:14:295620 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445621
[email protected]f7022f32014-08-21 16:32:195622 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5623 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445624}
5625
[email protected]e50efea2014-03-24 18:41:005626// Make sure redirects are cached, despite not reading their bodies.
5627TEST_F(URLRequestTestHTTP, CacheRedirect) {
5628 ASSERT_TRUE(test_server_.Start());
5629 GURL redirect_url =
5630 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5631
5632 {
5633 TestDelegate d;
davidben151423e2015-03-23 18:48:365634 scoped_ptr<URLRequest> req(
5635 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195636 req->Start();
[email protected]e50efea2014-03-24 18:41:005637 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195638 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005639 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195640 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005641 }
5642
5643 {
5644 TestDelegate d;
5645 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:365646 scoped_ptr<URLRequest> req(
5647 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195648 req->Start();
[email protected]e50efea2014-03-24 18:41:005649 base::RunLoop().Run();
5650
5651 EXPECT_EQ(1, d.received_redirect_count());
5652 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195653 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005654
[email protected]f7022f32014-08-21 16:32:195655 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:005656 base::RunLoop().Run();
5657 EXPECT_EQ(1, d.received_redirect_count());
5658 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195659 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5660 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005661 }
5662}
5663
5664// Make sure a request isn't cached when a NetworkDelegate forces a redirect
5665// when the headers are read, since the body won't have been read.
5666TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5667 ASSERT_TRUE(test_server_.Start());
5668 // URL that is normally cached.
5669 GURL initial_url = test_server_.GetURL("cachetime");
5670
5671 {
5672 // Set up the TestNetworkDelegate tp force a redirect.
5673 GURL redirect_to_url = test_server_.GetURL("echo");
5674 default_network_delegate_.set_redirect_on_headers_received_url(
5675 redirect_to_url);
5676
5677 TestDelegate d;
davidben151423e2015-03-23 18:48:365678 scoped_ptr<URLRequest> req(
5679 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195680 req->Start();
[email protected]e50efea2014-03-24 18:41:005681 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195682 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005683 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195684 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:005685 }
5686
5687 {
5688 TestDelegate d;
davidben151423e2015-03-23 18:48:365689 scoped_ptr<URLRequest> req(
5690 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195691 req->Start();
[email protected]e50efea2014-03-24 18:41:005692 base::RunLoop().Run();
5693
[email protected]f7022f32014-08-21 16:32:195694 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5695 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005696 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195697 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:005698 }
5699}
5700
[email protected]5f714132014-03-26 10:41:165701// Tests that redirection to an unsafe URL is allowed when it has been marked as
5702// safe.
5703TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5704 ASSERT_TRUE(test_server_.Start());
5705
5706 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5707 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5708 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5709
5710 TestDelegate d;
5711 {
[email protected]f7022f32014-08-21 16:32:195712 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365713 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165714
[email protected]f7022f32014-08-21 16:32:195715 r->Start();
[email protected]5f714132014-03-26 10:41:165716 base::RunLoop().Run();
5717
[email protected]f7022f32014-08-21 16:32:195718 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:165719
[email protected]f7022f32014-08-21 16:32:195720 EXPECT_EQ(2U, r->url_chain().size());
5721 EXPECT_EQ(OK, r->status().error());
5722 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:165723 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5724 }
5725}
5726
5727// Tests that a redirect to a different unsafe URL is blocked, even after adding
5728// some other URL to the whitelist.
5729TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5730 ASSERT_TRUE(test_server_.Start());
5731
5732 GURL unsafe_url("data:text/html,something");
5733 GURL different_unsafe_url("data:text/html,something-else");
5734 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5735 default_network_delegate_.set_allowed_unsafe_redirect_url(
5736 different_unsafe_url);
5737
5738 TestDelegate d;
5739 {
[email protected]f7022f32014-08-21 16:32:195740 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365741 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165742
[email protected]f7022f32014-08-21 16:32:195743 r->Start();
[email protected]5f714132014-03-26 10:41:165744 base::RunLoop().Run();
5745
[email protected]f7022f32014-08-21 16:32:195746 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5747 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:165748 }
5749}
5750
[email protected]5f714132014-03-26 10:41:165751// Redirects from an URL with fragment to an unsafe URL with fragment should
5752// be allowed, and the reference fragment of the target URL should be preserved.
5753TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5754 ASSERT_TRUE(test_server_.Start());
5755
5756 GURL original_url(test_server_.GetURL("original#fragment1"));
5757 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5758 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5759
5760 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5761 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5762
5763 TestDelegate d;
5764 {
davidben151423e2015-03-23 18:48:365765 scoped_ptr<URLRequest> r(
5766 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165767
[email protected]f7022f32014-08-21 16:32:195768 r->Start();
[email protected]5f714132014-03-26 10:41:165769 base::RunLoop().Run();
5770
[email protected]f7022f32014-08-21 16:32:195771 EXPECT_EQ(2U, r->url_chain().size());
5772 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5773 EXPECT_EQ(OK, r->status().error());
5774 EXPECT_EQ(original_url, r->original_url());
5775 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:165776 }
5777}
5778
5779// When a delegate has specified a safe redirect URL, but it does not match the
5780// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:145781TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:165782 ASSERT_TRUE(test_server_.Start());
5783
5784 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5785 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5786 GURL redirect_url(test_server_.GetURL("target"));
5787 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5788
5789 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5790 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5791
5792 TestDelegate d;
5793 {
davidben151423e2015-03-23 18:48:365794 scoped_ptr<URLRequest> r(
5795 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165796
[email protected]f7022f32014-08-21 16:32:195797 r->Start();
[email protected]5f714132014-03-26 10:41:165798 base::RunLoop().Run();
5799
[email protected]f7022f32014-08-21 16:32:195800 EXPECT_EQ(2U, r->url_chain().size());
5801 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5802 EXPECT_EQ(OK, r->status().error());
5803 EXPECT_EQ(original_url, r->original_url());
5804 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:165805 }
5806}
5807
[email protected]f878230e2014-04-03 15:36:145808// When a delegate has specified a safe redirect URL, assume that the redirect
5809// URL should not be changed. In particular, the reference fragment should not
5810// be modified.
5811TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5812 ASSERT_TRUE(test_server_.Start());
5813
5814 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5815 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5816
5817 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5818 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5819
5820 TestDelegate d;
5821 {
davidben151423e2015-03-23 18:48:365822 scoped_ptr<URLRequest> r(
5823 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145824
[email protected]f7022f32014-08-21 16:32:195825 r->Start();
[email protected]f878230e2014-04-03 15:36:145826 base::RunLoop().Run();
5827
[email protected]f7022f32014-08-21 16:32:195828 EXPECT_EQ(2U, r->url_chain().size());
5829 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5830 EXPECT_EQ(OK, r->status().error());
5831 EXPECT_EQ(original_url, r->original_url());
5832 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145833 }
5834}
5835
5836// When a URLRequestRedirectJob is created, the redirection must be followed and
5837// the reference fragment of the target URL must not be modified.
5838TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5839 ASSERT_TRUE(test_server_.Start());
5840
5841 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5842 GURL redirect_url(test_server_.GetURL("echo"));
5843
5844 TestDelegate d;
davidben151423e2015-03-23 18:48:365845 scoped_ptr<URLRequest> r(
5846 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145847
5848 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:195849 r.get(), &default_network_delegate_, redirect_url,
[email protected]f878230e2014-04-03 15:36:145850 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5851 AddTestInterceptor()->set_main_intercept_job(job);
5852
[email protected]f7022f32014-08-21 16:32:195853 r->Start();
[email protected]f878230e2014-04-03 15:36:145854 base::RunLoop().Run();
5855
[email protected]f7022f32014-08-21 16:32:195856 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5857 EXPECT_EQ(OK, r->status().error());
5858 EXPECT_EQ(original_url, r->original_url());
5859 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145860}
5861
[email protected]316c1e5e2012-09-12 15:17:445862TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5863 ASSERT_TRUE(test_server_.Start());
5864
5865 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195866 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365867 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195868 req->SetReferrer("http://user:[email protected]/");
5869 req->Start();
[email protected]255620da2013-08-19 13:14:295870 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445871
5872 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5873}
5874
[email protected]99ecf6e2013-04-10 22:46:135875TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5876 ASSERT_TRUE(test_server_.Start());
5877
5878 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195879 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365880 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195881 req->SetReferrer("http://foo.com/test#fragment");
5882 req->Start();
[email protected]255620da2013-08-19 13:14:295883 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135884
5885 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5886}
5887
5888TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5889 ASSERT_TRUE(test_server_.Start());
5890
5891 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195892 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365893 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195894 req->SetReferrer("http://foo.com/test#fragment");
5895 req->SetReferrer("");
5896 req->Start();
[email protected]255620da2013-08-19 13:14:295897 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135898
5899 EXPECT_EQ(std::string("None"), d.data_received());
5900}
5901
[email protected]1826a402014-01-08 15:40:485902// Defer network start and then resume, checking that the request was a success
5903// and bytes were received.
5904TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5905 ASSERT_TRUE(test_server_.Start());
5906
5907 TestDelegate d;
5908 {
5909 d.set_quit_on_network_start(true);
5910 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365911 scoped_ptr<URLRequest> req(
5912 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485913
[email protected]f7022f32014-08-21 16:32:195914 req->Start();
[email protected]1826a402014-01-08 15:40:485915 base::RunLoop().Run();
5916
5917 EXPECT_EQ(1, d.received_before_network_start_count());
5918 EXPECT_EQ(0, d.response_started_count());
5919
[email protected]f7022f32014-08-21 16:32:195920 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485921 base::RunLoop().Run();
5922
5923 EXPECT_EQ(1, d.response_started_count());
5924 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195925 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485926 }
5927}
5928
5929// Check that OnBeforeNetworkStart is only called once even if there is a
5930// redirect.
5931TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5932 ASSERT_TRUE(test_server_.Start());
5933
5934 TestDelegate d;
5935 {
5936 d.set_quit_on_redirect(true);
5937 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:195938 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365939 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485940
[email protected]f7022f32014-08-21 16:32:195941 req->Start();
[email protected]1826a402014-01-08 15:40:485942 base::RunLoop().Run();
5943
5944 EXPECT_EQ(1, d.received_before_network_start_count());
5945 EXPECT_EQ(0, d.response_started_count());
5946 EXPECT_EQ(0, d.received_redirect_count());
5947
[email protected]f7022f32014-08-21 16:32:195948 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485949 base::RunLoop().Run();
5950
5951 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195952 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:485953 base::RunLoop().Run();
5954
5955 // Check that the redirect's new network transaction does not get propagated
5956 // to a second OnBeforeNetworkStart() notification.
5957 EXPECT_EQ(1, d.received_before_network_start_count());
5958
5959 EXPECT_EQ(1, d.response_started_count());
5960 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195961 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485962 }
5963}
5964
5965// Cancel the request after learning that the request would use the network.
5966TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5967 ASSERT_TRUE(test_server_.Start());
5968
5969 TestDelegate d;
5970 {
5971 d.set_quit_on_network_start(true);
5972 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365973 scoped_ptr<URLRequest> req(
5974 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485975
[email protected]f7022f32014-08-21 16:32:195976 req->Start();
[email protected]1826a402014-01-08 15:40:485977 base::RunLoop().Run();
5978
5979 EXPECT_EQ(1, d.received_before_network_start_count());
5980 EXPECT_EQ(0, d.response_started_count());
5981
[email protected]f7022f32014-08-21 16:32:195982 req->Cancel();
[email protected]1826a402014-01-08 15:40:485983 base::RunLoop().Run();
5984
5985 EXPECT_EQ(1, d.response_started_count());
5986 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195987 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:485988 }
5989}
5990
[email protected]316c1e5e2012-09-12 15:17:445991TEST_F(URLRequestTestHTTP, CancelRedirect) {
5992 ASSERT_TRUE(test_server_.Start());
5993
5994 TestDelegate d;
5995 {
5996 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:195997 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365998 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195999 req->Start();
[email protected]255620da2013-08-19 13:14:296000 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446001
6002 EXPECT_EQ(1, d.response_started_count());
6003 EXPECT_EQ(0, d.bytes_received());
6004 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196005 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446006 }
6007}
6008
6009TEST_F(URLRequestTestHTTP, DeferredRedirect) {
6010 ASSERT_TRUE(test_server_.Start());
6011
6012 TestDelegate d;
6013 {
6014 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:046015 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366016 scoped_ptr<URLRequest> req(
6017 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046018
[email protected]f7022f32014-08-21 16:32:196019 req->Start();
[email protected]255620da2013-08-19 13:14:296020 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446021
6022 EXPECT_EQ(1, d.received_redirect_count());
6023
[email protected]f7022f32014-08-21 16:32:196024 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296025 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446026
6027 EXPECT_EQ(1, d.response_started_count());
6028 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196029 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446030
[email protected]6cdfd7f2013-02-08 20:40:156031 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446032 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476033 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446034 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6035
6036 std::string contents;
[email protected]82f84b92013-08-30 18:23:506037 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446038 EXPECT_EQ(contents, d.data_received());
6039 }
6040}
6041
[email protected]79e1fd62013-06-20 06:50:046042TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
6043 ASSERT_TRUE(test_server_.Start());
6044
6045 TestDelegate d;
6046 {
6047 d.set_quit_on_redirect(true);
6048 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366049 scoped_ptr<URLRequest> req(
6050 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046051
6052 EXPECT_FALSE(d.have_full_request_headers());
6053
[email protected]f7022f32014-08-21 16:32:196054 req->Start();
[email protected]255620da2013-08-19 13:14:296055 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046056
6057 EXPECT_EQ(1, d.received_redirect_count());
6058 EXPECT_TRUE(d.have_full_request_headers());
6059 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6060 d.ClearFullRequestHeaders();
6061
[email protected]f7022f32014-08-21 16:32:196062 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296063 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046064
6065 GURL target_url(test_server_.GetURL("files/with-headers.html"));
6066 EXPECT_EQ(1, d.response_started_count());
6067 EXPECT_TRUE(d.have_full_request_headers());
6068 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6069 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196070 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046071
6072 base::FilePath path;
6073 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476074 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046075 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6076
6077 std::string contents;
[email protected]82f84b92013-08-30 18:23:506078 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046079 EXPECT_EQ(contents, d.data_received());
6080 }
6081}
6082
[email protected]316c1e5e2012-09-12 15:17:446083TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
6084 ASSERT_TRUE(test_server_.Start());
6085
6086 TestDelegate d;
6087 {
6088 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196089 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366090 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196091 req->Start();
[email protected]255620da2013-08-19 13:14:296092 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446093
6094 EXPECT_EQ(1, d.received_redirect_count());
6095
[email protected]f7022f32014-08-21 16:32:196096 req->Cancel();
[email protected]255620da2013-08-19 13:14:296097 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446098
6099 EXPECT_EQ(1, d.response_started_count());
6100 EXPECT_EQ(0, d.bytes_received());
6101 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196102 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446103 }
6104}
6105
6106TEST_F(URLRequestTestHTTP, VaryHeader) {
6107 ASSERT_TRUE(test_server_.Start());
6108
[email protected]3b23a222013-05-15 21:33:256109 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446110 {
6111 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196112 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366113 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446114 HttpRequestHeaders headers;
6115 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196116 req->SetExtraRequestHeaders(headers);
6117 req->Start();
[email protected]255620da2013-08-19 13:14:296118 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256119
6120 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196121 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256122 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446123 }
6124
[email protected]3b23a222013-05-15 21:33:256125 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446126 {
6127 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196128 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366129 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446130 HttpRequestHeaders headers;
6131 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196132 req->SetExtraRequestHeaders(headers);
6133 req->Start();
[email protected]255620da2013-08-19 13:14:296134 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446135
[email protected]f7022f32014-08-21 16:32:196136 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256137
6138 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196139 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256140 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446141 }
6142
[email protected]3b23a222013-05-15 21:33:256143 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446144 {
6145 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196146 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366147 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446148 HttpRequestHeaders headers;
6149 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196150 req->SetExtraRequestHeaders(headers);
6151 req->Start();
[email protected]255620da2013-08-19 13:14:296152 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446153
[email protected]f7022f32014-08-21 16:32:196154 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256155
6156 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196157 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256158 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446159 }
6160}
6161
6162TEST_F(URLRequestTestHTTP, BasicAuth) {
6163 ASSERT_TRUE(test_server_.Start());
6164
6165 // populate the cache
6166 {
6167 TestDelegate d;
6168 d.set_credentials(AuthCredentials(kUser, kSecret));
6169
[email protected]f7022f32014-08-21 16:32:196170 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366171 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196172 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446173
[email protected]255620da2013-08-19 13:14:296174 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446175
6176 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6177 }
6178
6179 // repeat request with end-to-end validation. since auth-basic results in a
6180 // cachable page, we expect this test to result in a 304. in which case, the
6181 // response should be fetched from the cache.
6182 {
6183 TestDelegate d;
6184 d.set_credentials(AuthCredentials(kUser, kSecret));
6185
[email protected]f7022f32014-08-21 16:32:196186 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366187 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196188 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6189 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446190
[email protected]255620da2013-08-19 13:14:296191 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446192
6193 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6194
6195 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196196 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446197 }
6198}
6199
6200// Check that Set-Cookie headers in 401 responses are respected.
6201// http://crbug.com/6450
6202TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6203 ASSERT_TRUE(test_server_.Start());
6204
6205 GURL url_requiring_auth =
6206 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6207
6208 // Request a page that will give a 401 containing a Set-Cookie header.
6209 // Verify that when the transaction is restarted, it includes the new cookie.
6210 {
[email protected]ceefd7fd2012-11-29 00:36:246211 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446212 TestURLRequestContext context(true);
6213 context.set_network_delegate(&network_delegate);
6214 context.Init();
6215
6216 TestDelegate d;
6217 d.set_credentials(AuthCredentials(kUser, kSecret));
6218
davidben151423e2015-03-23 18:48:366219 scoped_ptr<URLRequest> r(
6220 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196221 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446222
[email protected]255620da2013-08-19 13:14:296223 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446224
6225 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6226
6227 // Make sure we sent the cookie in the restarted transaction.
6228 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6229 != std::string::npos);
6230 }
6231
6232 // Same test as above, except this time the restart is initiated earlier
6233 // (without user intervention since identity is embedded in the URL).
6234 {
[email protected]ceefd7fd2012-11-29 00:36:246235 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446236 TestURLRequestContext context(true);
6237 context.set_network_delegate(&network_delegate);
6238 context.Init();
6239
6240 TestDelegate d;
6241
6242 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186243 replacements.SetUsernameStr("user2");
6244 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446245 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6246
davidben151423e2015-03-23 18:48:366247 scoped_ptr<URLRequest> r(
6248 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196249 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446250
[email protected]255620da2013-08-19 13:14:296251 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446252
6253 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6254
6255 // Make sure we sent the cookie in the restarted transaction.
6256 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6257 != std::string::npos);
6258 }
6259}
6260
[email protected]58e32bb2013-01-21 18:23:256261// Tests that load timing works as expected with auth and the cache.
6262TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6263 ASSERT_TRUE(test_server_.Start());
6264
6265 // populate the cache
6266 {
6267 TestDelegate d;
6268 d.set_credentials(AuthCredentials(kUser, kSecret));
6269
[email protected]f7022f32014-08-21 16:32:196270 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366271 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196272 r->Start();
[email protected]58e32bb2013-01-21 18:23:256273
[email protected]255620da2013-08-19 13:14:296274 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256275
6276 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6277
6278 LoadTimingInfo load_timing_info_before_auth;
6279 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6280 &load_timing_info_before_auth));
6281 TestLoadTimingNotReused(load_timing_info_before_auth,
6282 CONNECT_TIMING_HAS_DNS_TIMES);
6283
6284 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196285 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256286 // The test server does not support keep alive sockets, so the second
6287 // request with auth should use a new socket.
6288 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6289 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6290 load_timing_info.socket_log_id);
6291 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6292 load_timing_info.connect_timing.connect_start);
6293 }
6294
[email protected]3b23a222013-05-15 21:33:256295 // Repeat request with end-to-end validation. Since auth-basic results in a
6296 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256297 // response should be fetched from the cache.
6298 {
6299 TestDelegate d;
6300 d.set_credentials(AuthCredentials(kUser, kSecret));
6301
[email protected]f7022f32014-08-21 16:32:196302 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366303 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196304 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6305 r->Start();
[email protected]58e32bb2013-01-21 18:23:256306
[email protected]255620da2013-08-19 13:14:296307 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256308
6309 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6310
6311 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196312 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256313
[email protected]3b23a222013-05-15 21:33:256314 // Since there was a request that went over the wire, the load timing
6315 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256316 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196317 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256318 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256319 }
6320}
6321
[email protected]316c1e5e2012-09-12 15:17:446322// In this test, we do a POST which the server will 302 redirect.
6323// The subsequent transaction should use GET, and should not send the
6324// Content-Type header.
6325// http://code.google.com/p/chromium/issues/detail?id=843
6326TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6327 ASSERT_TRUE(test_server_.Start());
6328
6329 const char kData[] = "hello world";
6330
6331 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196332 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366333 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196334 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076335 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446336
6337 // Set headers (some of which are specific to the POST).
6338 HttpRequestHeaders headers;
6339 headers.AddHeadersFromString(
6340 "Content-Type: multipart/form-data; "
6341 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6342 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6343 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6344 "Accept-Language: en-US,en\r\n"
6345 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6346 "Content-Length: 11\r\n"
6347 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196348 req->SetExtraRequestHeaders(headers);
6349 req->Start();
[email protected]255620da2013-08-19 13:14:296350 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446351
6352 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196353 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446354 EXPECT_EQ("text/html", mime_type);
6355
6356 const std::string& data = d.data_received();
6357
6358 // Check that the post-specific headers were stripped:
6359 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6360 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6361 EXPECT_FALSE(ContainsString(data, "Origin:"));
6362
6363 // These extra request headers should not have been stripped.
6364 EXPECT_TRUE(ContainsString(data, "Accept:"));
6365 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6366 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6367}
6368
jww5fe460ff2015-03-28 00:22:516369// The following tests check that we handle mutating the request for HTTP
6370// redirects as expected.
6371// See https://crbug.com/56373, https://crbug.com/102130, and
6372// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:446373
6374TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6375 ASSERT_TRUE(test_server_.Start());
6376
6377 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:516378 const GURL https_redirect_url =
6379 test_server_.GetURL("files/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:446380
6381 HTTPRedirectMethodTest(url, "POST", "GET", true);
6382 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6383 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516384
6385 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6386 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6387 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6388 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6389 std::string());
[email protected]316c1e5e2012-09-12 15:17:446390}
6391
6392TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6393 ASSERT_TRUE(test_server_.Start());
6394
6395 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:516396 const GURL https_redirect_url =
6397 test_server_.GetURL("files/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:446398
6399 HTTPRedirectMethodTest(url, "POST", "GET", true);
6400 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6401 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516402
6403 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6404 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6405 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6406 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6407 std::string());
[email protected]316c1e5e2012-09-12 15:17:446408}
6409
6410TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6411 ASSERT_TRUE(test_server_.Start());
6412
6413 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:516414 const GURL https_redirect_url =
6415 test_server_.GetURL("files/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:446416
6417 HTTPRedirectMethodTest(url, "POST", "GET", true);
6418 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6419 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516420
6421 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6422 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6423 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6424 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6425 std::string());
[email protected]316c1e5e2012-09-12 15:17:446426}
6427
6428TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6429 ASSERT_TRUE(test_server_.Start());
6430
6431 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:516432 const GURL https_redirect_url =
6433 test_server_.GetURL("files/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:446434
6435 HTTPRedirectMethodTest(url, "POST", "POST", true);
6436 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6437 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516438
6439 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6440 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6441 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6442 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:446443}
6444
[email protected]0a17aab32014-04-24 03:32:376445TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6446 ASSERT_TRUE(test_server_.Start());
6447
6448 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:516449 const GURL https_redirect_url =
6450 test_server_.GetURL("files/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:376451
6452 HTTPRedirectMethodTest(url, "POST", "POST", true);
6453 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6454 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516455
6456 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6457 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6458 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6459 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:376460}
6461
6462// Make sure that 308 responses without bodies are not treated as redirects.
6463// Certain legacy apis that pre-date the response code expect this behavior
6464// (Like Google Drive).
6465TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6466 ASSERT_TRUE(test_server_.Start());
6467
6468 TestDelegate d;
6469 const GURL url = test_server_.GetURL("files/308-without-location-header");
6470
davidben151423e2015-03-23 18:48:366471 scoped_ptr<URLRequest> request(
6472 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:376473
[email protected]f7022f32014-08-21 16:32:196474 request->Start();
[email protected]0a17aab32014-04-24 03:32:376475 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196476 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6477 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:376478 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196479 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:376480 EXPECT_EQ("This is not a redirect.", d.data_received());
6481}
6482
[email protected]f878230e2014-04-03 15:36:146483TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6484 ASSERT_TRUE(test_server_.Start());
6485
6486 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6487 GURL expected_url(test_server_.GetURL("echo#fragment"));
6488
6489 TestDelegate d;
6490 {
davidben151423e2015-03-23 18:48:366491 scoped_ptr<URLRequest> r(
6492 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146493
[email protected]f7022f32014-08-21 16:32:196494 r->Start();
[email protected]f878230e2014-04-03 15:36:146495 base::RunLoop().Run();
6496
[email protected]f7022f32014-08-21 16:32:196497 EXPECT_EQ(2U, r->url_chain().size());
6498 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6499 EXPECT_EQ(OK, r->status().error());
6500 EXPECT_EQ(original_url, r->original_url());
6501 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:146502 }
6503}
6504
[email protected]cba24642014-08-15 20:49:596505TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6506 ASSERT_TRUE(test_server_.Start());
6507
6508 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6509 GURL first_party_url("http://example.com");
6510
6511 TestDelegate d;
6512 {
davidben151423e2015-03-23 18:48:366513 scoped_ptr<URLRequest> r(
6514 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196515 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:596516
[email protected]f7022f32014-08-21 16:32:196517 r->Start();
[email protected]cba24642014-08-15 20:49:596518 base::RunLoop().Run();
6519
[email protected]f7022f32014-08-21 16:32:196520 EXPECT_EQ(2U, r->url_chain().size());
6521 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6522 EXPECT_EQ(OK, r->status().error());
6523 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596524 }
6525}
6526
6527TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6528 ASSERT_TRUE(test_server_.Start());
6529
6530 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6531 GURL original_first_party_url("http://example.com");
6532 GURL expected_first_party_url(test_server_.GetURL("echo"));
6533
6534 TestDelegate d;
6535 {
davidben151423e2015-03-23 18:48:366536 scoped_ptr<URLRequest> r(
6537 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196538 r->set_first_party_for_cookies(original_first_party_url);
6539 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:596540 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6541
[email protected]f7022f32014-08-21 16:32:196542 r->Start();
[email protected]cba24642014-08-15 20:49:596543 base::RunLoop().Run();
6544
[email protected]f7022f32014-08-21 16:32:196545 EXPECT_EQ(2U, r->url_chain().size());
6546 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6547 EXPECT_EQ(OK, r->status().error());
6548 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596549 }
6550}
6551
[email protected]316c1e5e2012-09-12 15:17:446552TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6553 ASSERT_TRUE(test_server_.Start());
6554
6555 const char kData[] = "hello world";
6556
6557 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196558 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366559 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196560 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076561 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446562 HttpRequestHeaders headers;
6563 headers.SetHeader(HttpRequestHeaders::kContentLength,
6564 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196565 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446566
6567 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196568 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096569 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446570 AddTestInterceptor()->set_main_intercept_job(job);
6571
[email protected]f7022f32014-08-21 16:32:196572 req->Start();
[email protected]255620da2013-08-19 13:14:296573 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196574 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:446575}
6576
6577TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6578 ASSERT_TRUE(test_server_.Start());
6579
6580 const char kData[] = "hello world";
6581
6582 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196583 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366584 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196585 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076586 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446587 HttpRequestHeaders headers;
6588 headers.SetHeader(HttpRequestHeaders::kContentLength,
6589 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196590 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446591
6592 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196593 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096594 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6595 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446596 AddTestInterceptor()->set_main_intercept_job(job);
6597
[email protected]f7022f32014-08-21 16:32:196598 req->Start();
[email protected]255620da2013-08-19 13:14:296599 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196600 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:446601 EXPECT_EQ(kData, d.data_received());
6602}
6603
6604// Check that default A-L header is sent.
6605TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6606 ASSERT_TRUE(test_server_.Start());
6607
[email protected]8790210c2013-12-02 05:29:536608 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:246609 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446610 TestURLRequestContext context(true);
6611 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:436612 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446613 context.Init();
6614
6615 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196616 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366617 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196618 req->Start();
[email protected]255620da2013-08-19 13:14:296619 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446620 EXPECT_EQ("en", d.data_received());
6621}
6622
6623// Check that an empty A-L header is not sent. http://crbug.com/77365.
6624TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6625 ASSERT_TRUE(test_server_.Start());
6626
[email protected]8790210c2013-12-02 05:29:536627 std::string empty_string; // Avoid most vexing parse on line below.
6628 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:246629 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446630 TestURLRequestContext context(true);
6631 context.set_network_delegate(&network_delegate);
6632 context.Init();
6633 // We override the language after initialization because empty entries
6634 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:436635 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446636
6637 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196638 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366639 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196640 req->Start();
[email protected]255620da2013-08-19 13:14:296641 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446642 EXPECT_EQ("None", d.data_received());
6643}
6644
6645// Check that if request overrides the A-L header, the default is not appended.
6646// See http://crbug.com/20894
6647TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6648 ASSERT_TRUE(test_server_.Start());
6649
6650 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196651 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366652 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446653 HttpRequestHeaders headers;
6654 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:196655 req->SetExtraRequestHeaders(headers);
6656 req->Start();
[email protected]255620da2013-08-19 13:14:296657 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446658 EXPECT_EQ(std::string("ru"), d.data_received());
6659}
6660
6661// Check that default A-E header is sent.
6662TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6663 ASSERT_TRUE(test_server_.Start());
6664
6665 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196666 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366667 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446668 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:196669 req->SetExtraRequestHeaders(headers);
6670 req->Start();
[email protected]255620da2013-08-19 13:14:296671 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446672 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6673}
6674
6675// Check that if request overrides the A-E header, the default is not appended.
6676// See http://crbug.com/47381
6677TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6678 ASSERT_TRUE(test_server_.Start());
6679
6680 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196681 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366682 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446683 HttpRequestHeaders headers;
6684 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:196685 req->SetExtraRequestHeaders(headers);
6686 req->Start();
[email protected]255620da2013-08-19 13:14:296687 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446688 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6689 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6690}
6691
[email protected]84f05432013-03-15 01:00:126692// Check that setting the A-C header sends the proper header.
6693TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:446694 ASSERT_TRUE(test_server_.Start());
6695
6696 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196697 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366698 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446699 HttpRequestHeaders headers;
6700 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:196701 req->SetExtraRequestHeaders(headers);
6702 req->Start();
[email protected]255620da2013-08-19 13:14:296703 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446704 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6705}
6706
6707// Check that default User-Agent header is sent.
6708TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6709 ASSERT_TRUE(test_server_.Start());
6710
6711 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196712 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366713 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196714 req->Start();
[email protected]255620da2013-08-19 13:14:296715 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196716 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:376717 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446718}
6719
6720// Check that if request overrides the User-Agent header,
6721// the default is not appended.
6722TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6723 ASSERT_TRUE(test_server_.Start());
6724
6725 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196726 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366727 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446728 HttpRequestHeaders headers;
6729 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:196730 req->SetExtraRequestHeaders(headers);
6731 req->Start();
[email protected]255620da2013-08-19 13:14:296732 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:356733 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446734}
6735
[email protected]ee4c30d2012-11-07 15:08:436736// Check that a NULL HttpUserAgentSettings causes the corresponding empty
6737// User-Agent header to be sent but does not send the Accept-Language and
6738// Accept-Charset headers.
6739TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6740 ASSERT_TRUE(test_server_.Start());
6741
[email protected]ceefd7fd2012-11-29 00:36:246742 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:436743 TestURLRequestContext context(true);
6744 context.set_network_delegate(&network_delegate);
6745 context.Init();
6746 // We override the HttpUserAgentSettings after initialization because empty
6747 // entries get overridden by Init().
6748 context.set_http_user_agent_settings(NULL);
6749
6750 struct {
6751 const char* request;
6752 const char* expected_response;
6753 } tests[] = { { "echoheader?Accept-Language", "None" },
6754 { "echoheader?Accept-Charset", "None" },
6755 { "echoheader?User-Agent", "" } };
6756
viettrungluue4a8b882014-10-16 06:17:386757 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:436758 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196759 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366760 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196761 req->Start();
[email protected]255620da2013-08-19 13:14:296762 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:436763 EXPECT_EQ(tests[i].expected_response, d.data_received())
6764 << " Request = \"" << tests[i].request << "\"";
6765 }
6766}
6767
[email protected]5033ab82013-03-22 20:17:466768// Make sure that URLRequest passes on its priority updates to
6769// newly-created jobs after the first one.
6770TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6771 ASSERT_TRUE(test_server_.Start());
6772
6773 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196774 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366775 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196776 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:466777
6778 scoped_refptr<URLRequestRedirectJob> redirect_job =
6779 new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196780 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096781 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:506782 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:466783
[email protected]f7022f32014-08-21 16:32:196784 req->SetPriority(LOW);
6785 req->Start();
6786 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:466787
6788 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:196789 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:506790 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:466791
6792 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:296793 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:466794 EXPECT_EQ(LOW, job->priority());
6795}
6796
[email protected]80abdad2014-03-15 00:20:546797// Check that creating a network request while entering/exiting suspend mode
6798// fails as it should. This is the only case where an HttpTransactionFactory
6799// does not return an HttpTransaction.
6800TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6801 // Create a new HttpNetworkLayer that thinks it's suspended.
6802 HttpNetworkSession::Params params;
6803 params.host_resolver = default_context_.host_resolver();
6804 params.cert_verifier = default_context_.cert_verifier();
6805 params.transport_security_state = default_context_.transport_security_state();
6806 params.proxy_service = default_context_.proxy_service();
6807 params.ssl_config_service = default_context_.ssl_config_service();
6808 params.http_auth_handler_factory =
6809 default_context_.http_auth_handler_factory();
6810 params.network_delegate = &default_network_delegate_;
6811 params.http_server_properties = default_context_.http_server_properties();
6812 scoped_ptr<HttpNetworkLayer> network_layer(
6813 new HttpNetworkLayer(new HttpNetworkSession(params)));
6814 network_layer->OnSuspend();
6815
6816 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6817 HttpCache::DefaultBackend::InMemory(0));
6818
6819 TestURLRequestContext context(true);
6820 context.set_http_transaction_factory(&http_cache);
6821 context.Init();
6822
6823 TestDelegate d;
davidben151423e2015-03-23 18:48:366824 scoped_ptr<URLRequest> req(
6825 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196826 req->Start();
[email protected]80abdad2014-03-15 00:20:546827 base::RunLoop().Run();
6828
6829 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196830 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6831 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546832}
6833
6834// Check that creating a network request while entering/exiting suspend mode
6835// fails as it should in the case there is no cache. This is the only case
6836// where an HttpTransactionFactory does not return an HttpTransaction.
6837TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6838 // Create a new HttpNetworkLayer that thinks it's suspended.
6839 HttpNetworkSession::Params params;
6840 params.host_resolver = default_context_.host_resolver();
6841 params.cert_verifier = default_context_.cert_verifier();
6842 params.transport_security_state = default_context_.transport_security_state();
6843 params.proxy_service = default_context_.proxy_service();
6844 params.ssl_config_service = default_context_.ssl_config_service();
6845 params.http_auth_handler_factory =
6846 default_context_.http_auth_handler_factory();
6847 params.network_delegate = &default_network_delegate_;
6848 params.http_server_properties = default_context_.http_server_properties();
6849 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6850 network_layer.OnSuspend();
6851
6852 TestURLRequestContext context(true);
6853 context.set_http_transaction_factory(&network_layer);
6854 context.Init();
6855
6856 TestDelegate d;
davidben151423e2015-03-23 18:48:366857 scoped_ptr<URLRequest> req(
6858 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196859 req->Start();
[email protected]80abdad2014-03-15 00:20:546860 base::RunLoop().Run();
6861
6862 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196863 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6864 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546865}
6866
ttuttlec0c828492015-05-15 01:25:556867TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
6868 ASSERT_TRUE(test_server_.Start());
6869
6870 TestDelegate d;
6871 GURL test_url(test_server_.GetURL(std::string()));
6872 scoped_ptr<URLRequest> req(
6873 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
6874
6875 req->Start();
6876 base::RunLoop().Run();
6877
6878 EXPECT_TRUE(req->response_info().network_accessed);
6879}
6880
6881TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
6882 ASSERT_TRUE(test_server_.Start());
6883
6884 // Populate the cache.
6885 TestDelegate d;
6886 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6887 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
6888 req->Start();
6889 base::RunLoop().Run();
6890
6891 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6892 EXPECT_TRUE(req->response_info().network_accessed);
6893 EXPECT_FALSE(req->response_info().was_cached);
6894
6895 req = default_context_.CreateRequest(test_server_.GetURL("cachetime"),
6896 DEFAULT_PRIORITY, &d);
6897 req->Start();
6898 base::RunLoop().Run();
6899
6900 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6901 EXPECT_FALSE(req->response_info().network_accessed);
6902 EXPECT_TRUE(req->response_info().was_cached);
6903}
6904
6905TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
6906 ASSERT_TRUE(test_server_.Start());
6907
6908 TestDelegate d;
6909 GURL test_url(test_server_.GetURL(std::string()));
6910 scoped_ptr<URLRequest> req(
6911 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
6912 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
6913
6914 req->Start();
6915 base::RunLoop().Run();
6916
6917 EXPECT_FALSE(req->response_info().network_accessed);
6918}
6919
bengr1bf8e942014-11-07 01:36:506920class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
6921 public:
6922 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
6923 // ideally remove the dependency on URLRequestTestJob, and maybe move these
6924 // tests into the factory tests.
6925 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
6926 }
6927
6928 void SetUpFactory() override {
6929 interceptor_ = new MockURLRequestInterceptor();
6930 job_factory_.reset(new URLRequestInterceptingJobFactory(
6931 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
6932 }
6933
6934 MockURLRequestInterceptor* interceptor() const {
6935 return interceptor_;
6936 }
6937
6938 private:
6939 MockURLRequestInterceptor* interceptor_;
6940};
6941
6942TEST_F(URLRequestInterceptorTestHTTP,
6943 NetworkDelegateNotificationOnRedirectIntercept) {
6944 interceptor()->set_intercept_redirect(true);
6945 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
6946 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
6947
6948 ASSERT_TRUE(test_server()->Start());
6949
6950 TestDelegate d;
6951 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:366952 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:506953 req->Start();
6954 base::RunLoop().Run();
6955
6956 EXPECT_TRUE(interceptor()->did_intercept_redirect());
6957 // Check we got one good response
6958 EXPECT_TRUE(req->status().is_success());
6959 if (req->status().is_success())
6960 EXPECT_EQ(200, req->response_headers()->response_code());
6961
6962 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6963 EXPECT_EQ(1, d.response_started_count());
6964 EXPECT_EQ(0, d.received_redirect_count());
6965
6966 EXPECT_EQ(1, default_network_delegate()->created_requests());
6967 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6968 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
6969}
6970
6971TEST_F(URLRequestInterceptorTestHTTP,
6972 NetworkDelegateNotificationOnErrorIntercept) {
6973 // Intercept that error and respond with an OK response.
6974 interceptor()->set_intercept_final_response(true);
6975 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
6976 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
6977 default_network_delegate()->set_can_be_intercepted_on_error(true);
6978
6979 ASSERT_TRUE(test_server()->Start());
6980
6981 TestDelegate d;
6982 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6983 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366984 &d));
bengr1bf8e942014-11-07 01:36:506985 req->set_method("GET");
6986 req->Start();
6987 base::RunLoop().Run();
6988
6989 EXPECT_TRUE(interceptor()->did_intercept_final());
6990
6991 // Check we received one good response.
6992 EXPECT_TRUE(req->status().is_success());
6993 if (req->status().is_success())
6994 EXPECT_EQ(200, req->response_headers()->response_code());
6995 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6996 EXPECT_EQ(1, d.response_started_count());
6997 EXPECT_EQ(0, d.received_redirect_count());
6998
6999 EXPECT_EQ(1, default_network_delegate()->created_requests());
7000 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7001 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7002}
7003
7004TEST_F(URLRequestInterceptorTestHTTP,
7005 NetworkDelegateNotificationOnResponseIntercept) {
7006 // Intercept that error and respond with an OK response.
7007 interceptor()->set_intercept_final_response(true);
7008
7009 // Intercept with a real URLRequestHttpJob.
7010 interceptor()->set_use_url_request_http_job(true);
7011
7012 ASSERT_TRUE(test_server()->Start());
7013
7014 TestDelegate d;
7015 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:367016 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507017 req->set_method("GET");
7018 req->Start();
7019 base::RunLoop().Run();
7020
7021 EXPECT_TRUE(interceptor()->did_intercept_final());
7022
7023 // Check we received one good response.
7024 EXPECT_TRUE(req->status().is_success());
7025 if (req->status().is_success())
7026 EXPECT_EQ(200, req->response_headers()->response_code());
7027 EXPECT_EQ("hello", d.data_received());
7028 EXPECT_EQ(1, d.response_started_count());
7029 EXPECT_EQ(0, d.received_redirect_count());
7030
7031 EXPECT_EQ(1, default_network_delegate()->created_requests());
7032 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7033 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7034}
7035
mkwst0c5eab872014-11-21 14:18:547036class URLRequestTestReferrerPolicy : public URLRequestTest {
7037 public:
7038 URLRequestTestReferrerPolicy() {}
7039
7040 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
7041 origin_server_.reset(new SpawnedTestServer(
7042 origin_type, SpawnedTestServer::kLocalhost,
7043 origin_type == SpawnedTestServer::TYPE_HTTPS
7044 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477045 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547046 ASSERT_TRUE(origin_server_->Start());
7047 }
7048
7049 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
7050 SpawnedTestServer::Type destination_type) {
7051 origin_server_.reset(new SpawnedTestServer(
7052 origin_type, SpawnedTestServer::kLocalhost,
7053 origin_type == SpawnedTestServer::TYPE_HTTPS
7054 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477055 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547056 ASSERT_TRUE(origin_server_->Start());
7057
7058 destination_server_.reset(new SpawnedTestServer(
7059 destination_type, SpawnedTestServer::kLocalhost,
7060 destination_type == SpawnedTestServer::TYPE_HTTPS
7061 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477062 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547063 ASSERT_TRUE(destination_server_->Start());
7064 }
7065
7066 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7067 const GURL& referrer,
7068 const GURL& expected) {
7069 // Create and execute the request: we'll only have a |destination_server_|
7070 // if the origins are meant to be distinct. Otherwise, we'll use the
7071 // |origin_server_| for both endpoints.
7072 GURL destination_url =
7073 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
7074 : origin_server_->GetURL("echoheader?Referer");
7075 GURL origin_url =
7076 origin_server_->GetURL("server-redirect?" + destination_url.spec());
7077
7078 TestDelegate d;
7079 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367080 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547081 req->set_referrer_policy(policy);
7082 req->SetReferrer(referrer.spec());
7083 req->Start();
7084 base::RunLoop().Run();
7085
7086 EXPECT_EQ(1, d.response_started_count());
7087 EXPECT_EQ(1, d.received_redirect_count());
7088 EXPECT_EQ(destination_url, req->url());
7089 EXPECT_TRUE(req->status().is_success());
7090 EXPECT_EQ(200, req->response_headers()->response_code());
7091
7092 EXPECT_EQ(expected.spec(), req->referrer());
7093 if (expected.is_empty())
7094 EXPECT_EQ("None", d.data_received());
7095 else
7096 EXPECT_EQ(expected.spec(), d.data_received());
7097 }
7098
7099 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
7100
7101 private:
7102 scoped_ptr<SpawnedTestServer> origin_server_;
7103 scoped_ptr<SpawnedTestServer> destination_server_;
7104};
7105
7106TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
7107 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
7108
7109 VerifyReferrerAfterRedirect(
7110 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7111 origin_server()->GetURL("path/to/file.html"),
7112 origin_server()->GetURL("path/to/file.html"));
7113
7114 VerifyReferrerAfterRedirect(
7115 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7116 origin_server()->GetURL("path/to/file.html"),
7117 origin_server()->GetURL("path/to/file.html"));
7118
7119 VerifyReferrerAfterRedirect(
7120 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7121 origin_server()->GetURL("path/to/file.html"),
7122 origin_server()->GetURL("path/to/file.html"));
7123
7124 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7125 origin_server()->GetURL("path/to/file.html"),
7126 origin_server()->GetURL("path/to/file.html"));
7127}
7128
7129TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
7130 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7131 SpawnedTestServer::TYPE_HTTP);
7132
7133 VerifyReferrerAfterRedirect(
7134 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7135 origin_server()->GetURL("path/to/file.html"),
7136 origin_server()->GetURL("path/to/file.html"));
7137
7138 VerifyReferrerAfterRedirect(
7139 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7140 origin_server()->GetURL("path/to/file.html"),
7141 origin_server()->GetURL(std::string()));
7142
7143 VerifyReferrerAfterRedirect(
7144 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7145 origin_server()->GetURL("path/to/file.html"),
7146 origin_server()->GetURL(std::string()));
7147
7148 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7149 origin_server()->GetURL("path/to/file.html"),
7150 origin_server()->GetURL("path/to/file.html"));
7151}
7152
7153TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
7154 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
7155
7156 VerifyReferrerAfterRedirect(
7157 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7158 origin_server()->GetURL("path/to/file.html"),
7159 origin_server()->GetURL("path/to/file.html"));
7160
7161 VerifyReferrerAfterRedirect(
7162 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7163 origin_server()->GetURL("path/to/file.html"),
7164 origin_server()->GetURL("path/to/file.html"));
7165
7166 VerifyReferrerAfterRedirect(
7167 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7168 origin_server()->GetURL("path/to/file.html"),
7169 origin_server()->GetURL("path/to/file.html"));
7170
7171 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7172 origin_server()->GetURL("path/to/file.html"),
7173 origin_server()->GetURL("path/to/file.html"));
7174}
7175
7176TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7177 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7178 SpawnedTestServer::TYPE_HTTPS);
7179
7180 VerifyReferrerAfterRedirect(
7181 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7182 origin_server()->GetURL("path/to/file.html"),
7183 origin_server()->GetURL("path/to/file.html"));
7184
7185 VerifyReferrerAfterRedirect(
7186 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7187 origin_server()->GetURL("path/to/file.html"),
7188 origin_server()->GetURL(std::string()));
7189
7190 VerifyReferrerAfterRedirect(
7191 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7192 origin_server()->GetURL("path/to/file.html"),
7193 origin_server()->GetURL(std::string()));
7194
7195 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7196 origin_server()->GetURL("path/to/file.html"),
7197 origin_server()->GetURL("path/to/file.html"));
7198}
7199
7200TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7201 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7202 SpawnedTestServer::TYPE_HTTPS);
7203
7204 VerifyReferrerAfterRedirect(
7205 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7206 origin_server()->GetURL("path/to/file.html"),
7207 origin_server()->GetURL("path/to/file.html"));
7208
7209 VerifyReferrerAfterRedirect(
7210 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7211 origin_server()->GetURL("path/to/file.html"),
7212 origin_server()->GetURL(std::string()));
7213
7214 VerifyReferrerAfterRedirect(
7215 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7216 origin_server()->GetURL("path/to/file.html"),
7217 origin_server()->GetURL(std::string()));
7218
7219 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7220 origin_server()->GetURL("path/to/file.html"),
7221 origin_server()->GetURL("path/to/file.html"));
7222}
7223
7224TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7225 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7226 SpawnedTestServer::TYPE_HTTP);
7227
7228 VerifyReferrerAfterRedirect(
7229 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7230 origin_server()->GetURL("path/to/file.html"), GURL());
7231
7232 VerifyReferrerAfterRedirect(
7233 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7234 origin_server()->GetURL("path/to/file.html"), GURL());
7235
7236 VerifyReferrerAfterRedirect(
7237 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7238 origin_server()->GetURL("path/to/file.html"),
7239 origin_server()->GetURL(std::string()));
7240
7241 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7242 origin_server()->GetURL("path/to/file.html"),
7243 origin_server()->GetURL("path/to/file.html"));
7244}
7245
[email protected]73e0bba2009-02-19 22:57:097246class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507247 public:
[email protected]ef2bf422012-05-11 03:27:097248 HTTPSRequestTest() : default_context_(true) {
7249 default_context_.set_network_delegate(&default_network_delegate_);
7250 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507251 }
dcheng67be2b1f2014-10-27 21:47:297252 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507253
7254 protected:
[email protected]ceefd7fd2012-11-29 00:36:247255 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097256 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467257};
7258
[email protected]c044616e2013-02-20 02:01:267259TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227260 SpawnedTestServer test_server(
7261 SpawnedTestServer::TYPE_HTTPS,
7262 SpawnedTestServer::kLocalhost,
7263 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117264 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467265
[email protected]ea224582008-12-07 20:25:467266 TestDelegate d;
7267 {
[email protected]f7022f32014-08-21 16:32:197268 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367269 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197270 r->Start();
7271 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467272
[email protected]255620da2013-08-19 13:14:297273 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467274
7275 EXPECT_EQ(1, d.response_started_count());
7276 EXPECT_FALSE(d.received_data_before_response());
7277 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197278 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197279 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197280 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197281 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197282 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467283 }
[email protected]ea224582008-12-07 20:25:467284}
7285
[email protected]5774ada2010-07-15 06:30:547286TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227287 SpawnedTestServer::SSLOptions ssl_options(
7288 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7289 SpawnedTestServer test_server(
7290 SpawnedTestServer::TYPE_HTTPS,
7291 ssl_options,
7292 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117293 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337294
7295 bool err_allowed = true;
7296 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7297 TestDelegate d;
7298 {
7299 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197300 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367301 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337302
[email protected]f7022f32014-08-21 16:32:197303 r->Start();
7304 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337305
[email protected]255620da2013-08-19 13:14:297306 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337307
7308 EXPECT_EQ(1, d.response_started_count());
7309 EXPECT_FALSE(d.received_data_before_response());
7310 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177311 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337312 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197313 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177314 } else {
[email protected]bacff652009-03-31 17:50:337315 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177316 }
[email protected]bacff652009-03-31 17:50:337317 }
7318 }
7319}
7320
[email protected]5774ada2010-07-15 06:30:547321TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227322 SpawnedTestServer::SSLOptions ssl_options(
7323 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7324 SpawnedTestServer test_server(
7325 SpawnedTestServer::TYPE_HTTPS,
7326 ssl_options,
7327 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117328 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337329
7330 // Iterate from false to true, just so that we do the opposite of the
7331 // previous test in order to increase test coverage.
7332 bool err_allowed = false;
7333 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7334 TestDelegate d;
7335 {
7336 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197337 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367338 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337339
[email protected]f7022f32014-08-21 16:32:197340 r->Start();
7341 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337342
[email protected]255620da2013-08-19 13:14:297343 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337344
7345 EXPECT_EQ(1, d.response_started_count());
7346 EXPECT_FALSE(d.received_data_before_response());
7347 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177348 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337349 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197350 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177351 } else {
[email protected]bacff652009-03-31 17:50:337352 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177353 }
[email protected]bacff652009-03-31 17:50:337354 }
7355 }
7356}
[email protected]73e0bba2009-02-19 22:57:097357
davidbena4c9d062015-04-03 22:34:257358// Tests that servers which require a deprecated cipher suite still work.
7359TEST_F(HTTPSRequestTest, CipherFallbackTest) {
vishal.b62985ca92015-04-17 08:45:517360 TestNetLog net_log;
davidbena4c9d062015-04-03 22:34:257361 default_context_.set_net_log(&net_log);
7362
7363 SpawnedTestServer::SSLOptions ssl_options;
7364 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
7365 SpawnedTestServer test_server(
7366 SpawnedTestServer::TYPE_HTTPS, ssl_options,
7367 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7368 ASSERT_TRUE(test_server.Start());
7369
7370 TestDelegate d;
7371 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7372 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7373 r->Start();
7374 EXPECT_TRUE(r->is_pending());
7375
7376 base::RunLoop().Run();
7377
7378 EXPECT_EQ(1, d.response_started_count());
7379 EXPECT_FALSE(d.received_data_before_response());
7380 EXPECT_NE(0, d.bytes_received());
7381 CheckSSLInfo(r->ssl_info());
7382 EXPECT_EQ(test_server.host_port_pair().host(), r->GetSocketAddress().host());
7383 EXPECT_EQ(test_server.host_port_pair().port(), r->GetSocketAddress().port());
7384
7385 // No version downgrade should have been necessary.
7386 EXPECT_FALSE(r->ssl_info().connection_status &
7387 SSL_CONNECTION_VERSION_FALLBACK);
7388 int expected_version = SSL_CONNECTION_VERSION_TLS1_2;
7389 if (SSLClientSocket::GetMaxSupportedSSLVersion() <
7390 SSL_PROTOCOL_VERSION_TLS1_2) {
7391 expected_version = SSL_CONNECTION_VERSION_TLS1_1;
7392 }
7393 EXPECT_EQ(expected_version,
7394 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
7395
mmenke43758e62015-05-04 21:09:467396 TestNetLogEntry::List entries;
davidbena4c9d062015-04-03 22:34:257397 net_log.GetEntries(&entries);
7398 ExpectLogContainsSomewhere(entries, 0, NetLog::TYPE_SSL_CIPHER_FALLBACK,
7399 NetLog::PHASE_NONE);
7400}
7401
[email protected]316c1e5e2012-09-12 15:17:447402// This tests that a load of www.google.com with a certificate error sets
7403// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7404// the interstitial to be fatal.
7405TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227406 SpawnedTestServer::SSLOptions ssl_options(
7407 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7408 SpawnedTestServer test_server(
7409 SpawnedTestServer::TYPE_HTTPS,
7410 ssl_options,
7411 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447412 ASSERT_TRUE(test_server.Start());
7413
7414 // We require that the URL be www.google.com in order to pick up the
7415 // preloaded HSTS entries in the TransportSecurityState. This means that we
7416 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247417 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447418
7419 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247420 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447421 TestURLRequestContext context(true);
7422 context.set_network_delegate(&network_delegate);
7423 context.set_host_resolver(&host_resolver);
7424 TransportSecurityState transport_security_state;
7425 context.set_transport_security_state(&transport_security_state);
7426 context.Init();
7427
7428 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197429 scoped_ptr<URLRequest> r(context.CreateRequest(
7430 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367431 test_server.host_port_pair().port())),
7432 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447433
[email protected]f7022f32014-08-21 16:32:197434 r->Start();
7435 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447436
[email protected]255620da2013-08-19 13:14:297437 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447438
7439 EXPECT_EQ(1, d.response_started_count());
7440 EXPECT_FALSE(d.received_data_before_response());
7441 EXPECT_TRUE(d.have_certificate_errors());
7442 EXPECT_TRUE(d.certificate_errors_are_fatal());
7443}
7444
7445// This tests that cached HTTPS page loads do not cause any updates to the
7446// TransportSecurityState.
7447TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7448 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7449 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227450 SpawnedTestServer::SSLOptions ssl_options(
7451 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7452 SpawnedTestServer test_server(
7453 SpawnedTestServer::TYPE_HTTPS,
7454 ssl_options,
7455 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447456 ASSERT_TRUE(test_server.Start());
7457
[email protected]9e6968d2014-05-07 21:46:267458 // We require that the URL be www.google.com in order to pick up the static
7459 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7460 // that we have to use a MockHostResolver in order to direct www.google.com to
7461 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447462
7463 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247464 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447465 TestURLRequestContext context(true);
7466 context.set_network_delegate(&network_delegate);
7467 context.set_host_resolver(&host_resolver);
7468 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267469
martijnc0d6b622015-06-30 19:14:407470 TransportSecurityState::STSState static_sts_state;
7471 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:267472 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:407473 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:447474 context.set_transport_security_state(&transport_security_state);
7475 context.Init();
7476
martijnc0d6b622015-06-30 19:14:407477 TransportSecurityState::STSState dynamic_sts_state;
7478 TransportSecurityState::PKPState dynamic_pkp_state;
7479 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
7480 &dynamic_sts_state));
7481 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
7482 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:267483
[email protected]316c1e5e2012-09-12 15:17:447484 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197485 scoped_ptr<URLRequest> r(context.CreateRequest(
7486 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367487 test_server.host_port_pair().port())),
7488 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447489
[email protected]f7022f32014-08-21 16:32:197490 r->Start();
7491 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447492
[email protected]255620da2013-08-19 13:14:297493 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447494
7495 EXPECT_EQ(1, d.response_started_count());
7496 EXPECT_FALSE(d.received_data_before_response());
7497 EXPECT_TRUE(d.have_certificate_errors());
7498 EXPECT_TRUE(d.certificate_errors_are_fatal());
7499
[email protected]9e6968d2014-05-07 21:46:267500 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:407501 TransportSecurityState::STSState new_static_sts_state;
7502 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:267503 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:407504 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
7505 TransportSecurityState::STSState new_dynamic_sts_state;
7506 TransportSecurityState::PKPState new_dynamic_pkp_state;
7507 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
7508 "www.google.com", &new_dynamic_sts_state));
7509 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
7510 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:267511
martijnc0d6b622015-06-30 19:14:407512 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
7513 EXPECT_EQ(new_static_sts_state.include_subdomains,
7514 static_sts_state.include_subdomains);
7515 EXPECT_EQ(new_static_pkp_state.include_subdomains,
7516 static_pkp_state.include_subdomains);
7517 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.spki_hashes,
7518 static_pkp_state.spki_hashes));
7519 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.bad_spki_hashes,
7520 static_pkp_state.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:447521}
7522
[email protected]8ccc69f2012-11-28 19:52:147523// Make sure HSTS preserves a POST request's method and body.
7524TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7525 static const char kData[] = "hello world";
7526
[email protected]ce7d0cbc2013-05-03 18:57:227527 SpawnedTestServer::SSLOptions ssl_options(
7528 SpawnedTestServer::SSLOptions::CERT_OK);
7529 SpawnedTestServer test_server(
7530 SpawnedTestServer::TYPE_HTTPS,
7531 ssl_options,
7532 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:147533 ASSERT_TRUE(test_server.Start());
7534
7535
7536 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7537 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:227538 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7539 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:147540 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:147541
7542 // Force https for www.somewhere.com.
7543 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:207544 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7545 bool include_subdomains = false;
7546 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7547 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:147548
7549 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7550
7551 TestURLRequestContext context(true);
7552 context.set_host_resolver(&host_resolver);
7553 context.set_transport_security_state(&transport_security_state);
7554 context.set_network_delegate(&network_delegate);
7555 context.Init();
7556
7557 TestDelegate d;
7558 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7559 // cause a certificate error. Ignore the error.
7560 d.set_allow_certificate_errors(true);
7561
[email protected]f7022f32014-08-21 16:32:197562 scoped_ptr<URLRequest> req(context.CreateRequest(
7563 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:367564 test_server.host_port_pair().port())),
7565 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197566 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077567 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:147568
[email protected]f7022f32014-08-21 16:32:197569 req->Start();
[email protected]255620da2013-08-19 13:14:297570 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:147571
[email protected]f7022f32014-08-21 16:32:197572 EXPECT_EQ("https", req->url().scheme());
7573 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:147574 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:407575
7576 LoadTimingInfo load_timing_info;
7577 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7578 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7579 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:147580}
7581
rob4e0be1f2014-09-11 23:40:227582// Make sure that the CORS headers are added to cross-origin HSTS redirects.
7583TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7584 static const char kOriginHeaderValue[] = "http://www.example.com";
7585
7586 SpawnedTestServer::SSLOptions ssl_options(
7587 SpawnedTestServer::SSLOptions::CERT_OK);
7588 SpawnedTestServer test_server(
7589 SpawnedTestServer::TYPE_HTTPS,
7590 ssl_options,
7591 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7592 ASSERT_TRUE(test_server.Start());
7593
7594 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7595 // address, so a MockHostResolver is needed to redirect example.net to the
7596 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7597 MockHostResolver host_resolver;
7598
7599 TransportSecurityState transport_security_state;
7600 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7601 bool include_subdomains = false;
7602 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7603
7604 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7605
7606 MockCertVerifier cert_verifier;
7607 cert_verifier.set_default_result(OK);
7608
7609 TestURLRequestContext context(true);
7610 context.set_host_resolver(&host_resolver);
7611 context.set_transport_security_state(&transport_security_state);
7612 context.set_network_delegate(&network_delegate);
7613 context.set_cert_verifier(&cert_verifier);
7614 context.Init();
7615
7616 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7617 test_server.host_port_pair().port()));
7618 url::Replacements<char> replacements;
7619 const char kNewScheme[] = "https";
7620 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7621 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7622
7623 TestDelegate d;
7624 // Quit on redirect to allow response header inspection upon redirect.
7625 d.set_quit_on_redirect(true);
7626
davidben151423e2015-03-23 18:48:367627 scoped_ptr<URLRequest> req(
7628 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:227629 // Set Origin header to simulate a cross-origin request.
7630 HttpRequestHeaders request_headers;
7631 request_headers.SetHeader("Origin", kOriginHeaderValue);
7632 req->SetExtraRequestHeaders(request_headers);
7633
7634 req->Start();
7635 base::RunLoop().Run();
7636
7637 EXPECT_EQ(1, d.received_redirect_count());
7638
7639 const HttpResponseHeaders* headers = req->response_headers();
7640 std::string redirect_location;
7641 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7642 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7643
7644 std::string received_cors_header;
7645 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7646 &received_cors_header));
7647 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7648}
7649
Adam Ricecb76ac62015-02-20 05:33:257650// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
7651// are performed in net/websockets/websocket_end_to_end_test.cc.
7652TEST(WebSocketURLRequestTest, HSTSApplied) {
7653 TestNetworkDelegate network_delegate;
7654 TransportSecurityState transport_security_state;
7655 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7656 bool include_subdomains = false;
7657 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7658 TestURLRequestContext context(true);
7659 context.set_transport_security_state(&transport_security_state);
7660 context.set_network_delegate(&network_delegate);
7661 context.Init();
7662 GURL ws_url("ws://example.net/echo");
7663 TestDelegate delegate;
7664 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367665 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:257666 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
7667 EXPECT_TRUE(ws_url.SchemeIs("wss"));
7668}
7669
[email protected]316c1e5e2012-09-12 15:17:447670namespace {
7671
7672class SSLClientAuthTestDelegate : public TestDelegate {
7673 public:
7674 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7675 }
dchengb03027d2014-10-21 12:00:207676 void OnCertificateRequested(URLRequest* request,
7677 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:447678 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:347679 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:447680 }
7681 int on_certificate_requested_count() {
7682 return on_certificate_requested_count_;
7683 }
7684 private:
7685 int on_certificate_requested_count_;
7686};
7687
7688} // namespace
7689
7690// TODO(davidben): Test the rest of the code. Specifically,
7691// - Filtering which certificates to select.
7692// - Sending a certificate back.
7693// - Getting a certificate request in an SSL renegotiation sending the
7694// HTTP request.
7695TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227696 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447697 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:227698 SpawnedTestServer test_server(
7699 SpawnedTestServer::TYPE_HTTPS,
7700 ssl_options,
7701 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447702 ASSERT_TRUE(test_server.Start());
7703
7704 SSLClientAuthTestDelegate d;
7705 {
[email protected]f7022f32014-08-21 16:32:197706 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367707 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447708
[email protected]f7022f32014-08-21 16:32:197709 r->Start();
7710 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447711
[email protected]255620da2013-08-19 13:14:297712 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447713
7714 EXPECT_EQ(1, d.on_certificate_requested_count());
7715 EXPECT_FALSE(d.received_data_before_response());
7716 EXPECT_EQ(0, d.bytes_received());
7717
7718 // Send no certificate.
7719 // TODO(davidben): Get temporary client cert import (with keys) working on
7720 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:197721 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:447722
[email protected]255620da2013-08-19 13:14:297723 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447724
7725 EXPECT_EQ(1, d.response_started_count());
7726 EXPECT_FALSE(d.received_data_before_response());
7727 EXPECT_NE(0, d.bytes_received());
7728 }
7729}
7730
7731TEST_F(HTTPSRequestTest, ResumeTest) {
7732 // Test that we attempt a session resume when making two connections to the
7733 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:227734 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447735 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227736 SpawnedTestServer test_server(
7737 SpawnedTestServer::TYPE_HTTPS,
7738 ssl_options,
7739 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447740 ASSERT_TRUE(test_server.Start());
7741
7742 SSLClientSocket::ClearSessionCache();
7743
7744 {
7745 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197746 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367747 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447748
[email protected]f7022f32014-08-21 16:32:197749 r->Start();
7750 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447751
[email protected]255620da2013-08-19 13:14:297752 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447753
7754 EXPECT_EQ(1, d.response_started_count());
7755 }
7756
7757 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7758 CloseAllConnections();
7759
7760 {
7761 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197762 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367763 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447764
[email protected]f7022f32014-08-21 16:32:197765 r->Start();
7766 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447767
[email protected]255620da2013-08-19 13:14:297768 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447769
7770 // The response will look like;
7771 // insert abc
7772 // lookup abc
7773 // insert xyz
7774 //
7775 // With a newline at the end which makes the split think that there are
7776 // four lines.
7777
7778 EXPECT_EQ(1, d.response_started_count());
7779 std::vector<std::string> lines;
7780 base::SplitString(d.data_received(), '\n', &lines);
7781 ASSERT_EQ(4u, lines.size()) << d.data_received();
7782
7783 std::string session_id;
7784
7785 for (size_t i = 0; i < 2; i++) {
7786 std::vector<std::string> parts;
7787 base::SplitString(lines[i], '\t', &parts);
7788 ASSERT_EQ(2u, parts.size());
7789 if (i == 0) {
7790 EXPECT_EQ("insert", parts[0]);
7791 session_id = parts[1];
7792 } else {
7793 EXPECT_EQ("lookup", parts[0]);
7794 EXPECT_EQ(session_id, parts[1]);
7795 }
7796 }
7797 }
7798}
7799
Adam Langley32352ad2014-10-14 22:31:007800// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7801// the result of fetching "ssl-session-cache" from the test server, indicates
7802// that exactly two different sessions were inserted, with no lookups etc.
7803static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7804 std::vector<std::string> lines;
7805 base::SplitString(session_info, '\n', &lines);
7806 ASSERT_EQ(3u, lines.size()) << session_info;
7807
7808 std::string session_id;
7809 for (size_t i = 0; i < 2; i++) {
7810 std::vector<std::string> parts;
7811 base::SplitString(lines[i], '\t', &parts);
7812 ASSERT_EQ(2u, parts.size());
7813 EXPECT_EQ("insert", parts[0]);
7814 if (i == 0) {
7815 session_id = parts[1];
7816 } else {
7817 EXPECT_NE(session_id, parts[1]);
7818 }
7819 }
7820}
7821
[email protected]316c1e5e2012-09-12 15:17:447822TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7823 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7824 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:227825 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447826 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227827 SpawnedTestServer test_server(
7828 SpawnedTestServer::TYPE_HTTPS,
7829 ssl_options,
7830 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447831 ASSERT_TRUE(test_server.Start());
7832
7833 SSLClientSocket::ClearSessionCache();
7834
7835 {
7836 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197837 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367838 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447839
[email protected]f7022f32014-08-21 16:32:197840 r->Start();
7841 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447842
[email protected]255620da2013-08-19 13:14:297843 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447844
7845 EXPECT_EQ(1, d.response_started_count());
7846 }
7847
7848 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7849 HttpNetworkSession::Params params;
7850 params.host_resolver = default_context_.host_resolver();
7851 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:117852 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:447853 params.proxy_service = default_context_.proxy_service();
7854 params.ssl_config_service = default_context_.ssl_config_service();
7855 params.http_auth_handler_factory =
7856 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:417857 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:447858 params.http_server_properties = default_context_.http_server_properties();
7859 params.ssl_session_cache_shard = "alternate";
7860
[email protected]cba24642014-08-15 20:49:597861 scoped_ptr<HttpCache> cache(new HttpCache(
7862 new HttpNetworkSession(params),
7863 HttpCache::DefaultBackend::InMemory(0)));
[email protected]316c1e5e2012-09-12 15:17:447864
7865 default_context_.set_http_transaction_factory(cache.get());
7866
7867 {
7868 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197869 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367870 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447871
[email protected]f7022f32014-08-21 16:32:197872 r->Start();
7873 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447874
[email protected]255620da2013-08-19 13:14:297875 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447876
7877 // The response will look like;
7878 // insert abc
7879 // insert xyz
7880 //
7881 // With a newline at the end which makes the split think that there are
7882 // three lines.
7883
7884 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:007885 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447886 }
7887}
7888
davidben8ecc3072014-09-03 23:19:097889#if defined(OS_WIN)
7890
7891namespace {
7892
7893bool IsECDSACipherSuite(uint16_t cipher_suite) {
7894 const char* key_exchange;
7895 const char* cipher;
7896 const char* mac;
7897 bool is_aead;
7898 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7899 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7900}
7901
7902} // namespace
7903
7904// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7905// verified.
davidben9399c952014-10-07 04:09:117906TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:097907 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7908 LOG(INFO) << "Skipping test on this version.";
7909 return;
7910 }
7911
7912 SpawnedTestServer test_server(
7913 SpawnedTestServer::TYPE_HTTPS,
7914 SpawnedTestServer::kLocalhost,
7915 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7916 ASSERT_TRUE(test_server.Start());
7917
7918 TestDelegate d;
7919 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367920 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:097921 r->Start();
7922 EXPECT_TRUE(r->is_pending());
7923
7924 base::RunLoop().Run();
7925
7926 EXPECT_EQ(1, d.response_started_count());
7927 std::vector<std::string> lines;
7928 base::SplitString(d.data_received(), '\n', &lines);
7929
7930 for (size_t i = 0; i < lines.size(); i++) {
7931 int cipher_suite;
7932 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7933 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7934 << "ClientHello advertised " << cipher_suite;
7935 }
7936}
7937
7938#endif // OS_WIN
7939
Adam Langley32352ad2014-10-14 22:31:007940class TestSSLConfigService : public SSLConfigService {
7941 public:
7942 TestSSLConfigService(bool ev_enabled,
7943 bool online_rev_checking,
7944 bool rev_checking_required_local_anchors)
7945 : ev_enabled_(ev_enabled),
7946 online_rev_checking_(online_rev_checking),
7947 rev_checking_required_local_anchors_(
7948 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:027949 min_version_(kDefaultSSLVersionMin),
7950 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7951
7952 void set_min_version(uint16 version) {
7953 min_version_ = version;
7954 }
Adam Langley32352ad2014-10-14 22:31:007955
7956 void set_fallback_min_version(uint16 version) {
7957 fallback_min_version_ = version;
7958 }
7959
7960 // SSLConfigService:
dchengb03027d2014-10-21 12:00:207961 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:007962 *config = SSLConfig();
7963 config->rev_checking_enabled = online_rev_checking_;
7964 config->verify_ev_cert = ev_enabled_;
7965 config->rev_checking_required_local_anchors =
7966 rev_checking_required_local_anchors_;
7967 if (fallback_min_version_) {
7968 config->version_fallback_min = fallback_min_version_;
7969 }
Adam Langleyac6f24b42014-10-31 20:24:027970 if (min_version_) {
7971 config->version_min = min_version_;
7972 }
Adam Langley32352ad2014-10-14 22:31:007973 }
7974
7975 protected:
dchengb03027d2014-10-21 12:00:207976 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:007977
7978 private:
7979 const bool ev_enabled_;
7980 const bool online_rev_checking_;
7981 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:027982 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:007983 uint16 fallback_min_version_;
7984};
7985
7986class FallbackTestURLRequestContext : public TestURLRequestContext {
7987 public:
7988 explicit FallbackTestURLRequestContext(bool delay_initialization)
7989 : TestURLRequestContext(delay_initialization) {}
7990
7991 void set_fallback_min_version(uint16 version) {
7992 TestSSLConfigService *ssl_config_service =
7993 new TestSSLConfigService(true /* check for EV */,
7994 false /* online revocation checking */,
7995 false /* require rev. checking for local
7996 anchors */);
7997 ssl_config_service->set_fallback_min_version(version);
7998 set_ssl_config_service(ssl_config_service);
7999 }
8000};
8001
[email protected]48d2b7c52014-06-27 01:16:558002class HTTPSFallbackTest : public testing::Test {
8003 public:
Adam Langley32352ad2014-10-14 22:31:008004 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298005 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558006
8007 protected:
8008 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8009 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008010 context_.Init();
8011 delegate_.set_allow_certificate_errors(true);
8012
[email protected]48d2b7c52014-06-27 01:16:558013 SpawnedTestServer test_server(
8014 SpawnedTestServer::TYPE_HTTPS,
8015 ssl_options,
8016 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8017 ASSERT_TRUE(test_server.Start());
8018
davidben151423e2015-03-23 18:48:368019 request_ = context_.CreateRequest(test_server.GetURL(std::string()),
8020 DEFAULT_PRIORITY, &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558021 request_->Start();
8022
8023 base::RunLoop().Run();
8024 }
8025
Adam Langley32352ad2014-10-14 22:31:008026 void set_fallback_min_version(uint16 version) {
8027 context_.set_fallback_min_version(version);
8028 }
8029
[email protected]48d2b7c52014-06-27 01:16:558030 void ExpectConnection(int version) {
8031 EXPECT_EQ(1, delegate_.response_started_count());
8032 EXPECT_NE(0, delegate_.bytes_received());
8033 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8034 request_->ssl_info().connection_status));
8035 EXPECT_TRUE(request_->ssl_info().connection_status &
8036 SSL_CONNECTION_VERSION_FALLBACK);
8037 }
8038
8039 void ExpectFailure(int error) {
8040 EXPECT_EQ(1, delegate_.response_started_count());
8041 EXPECT_FALSE(request_->status().is_success());
8042 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8043 EXPECT_EQ(error, request_->status().error());
8044 }
8045
8046 private:
8047 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008048 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558049 scoped_ptr<URLRequest> request_;
8050};
8051
davidbenb127ca82015-06-15 19:05:428052// Tests the TLS 1.0 fallback doesn't happen.
8053TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558054 SpawnedTestServer::SSLOptions ssl_options(
8055 SpawnedTestServer::SSLOptions::CERT_OK);
8056 ssl_options.tls_intolerant =
8057 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8058
8059 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428060 ExpectFailure(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION);
8061}
8062
8063// Tests the TLS 1.1 fallback.
8064TEST_F(HTTPSFallbackTest, TLSv1_1Fallback) {
8065 if (SSLClientSocket::GetMaxSupportedSSLVersion() <
davidbenf310c422015-06-16 23:46:548066 SSL_PROTOCOL_VERSION_TLS1_2) {
davidbenb127ca82015-06-15 19:05:428067 return;
8068 }
8069
8070 SpawnedTestServer::SSLOptions ssl_options(
8071 SpawnedTestServer::SSLOptions::CERT_OK);
8072 ssl_options.tls_intolerant =
8073 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8074
8075 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8076 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
8077}
8078
8079// Tests that the TLS 1.1 fallback triggers on closed connections.
8080TEST_F(HTTPSFallbackTest, TLSv1_1FallbackClosed) {
8081 if (SSLClientSocket::GetMaxSupportedSSLVersion() <
davidbenf310c422015-06-16 23:46:548082 SSL_PROTOCOL_VERSION_TLS1_2) {
davidbenb127ca82015-06-15 19:05:428083 return;
8084 }
8085
8086 SpawnedTestServer::SSLOptions ssl_options(
8087 SpawnedTestServer::SSLOptions::CERT_OK);
8088 ssl_options.tls_intolerant =
8089 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8090 ssl_options.tls_intolerance_type =
8091 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8092
8093 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8094 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558095}
8096
8097// This test is disabled on Android because the remote test server doesn't cause
8098// a TCP reset.
8099#if !defined(OS_ANDROID)
davidbenb127ca82015-06-15 19:05:428100// Tests fallback to TLS 1.1 on connection reset.
8101TEST_F(HTTPSFallbackTest, TLSv1_1FallbackReset) {
8102 if (SSLClientSocket::GetMaxSupportedSSLVersion() <
davidbenf310c422015-06-16 23:46:548103 SSL_PROTOCOL_VERSION_TLS1_2) {
davidbenb127ca82015-06-15 19:05:428104 return;
8105 }
8106
[email protected]48d2b7c52014-06-27 01:16:558107 SpawnedTestServer::SSLOptions ssl_options(
8108 SpawnedTestServer::SSLOptions::CERT_OK);
8109 ssl_options.tls_intolerant =
davidbenb127ca82015-06-15 19:05:428110 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
[email protected]48d2b7c52014-06-27 01:16:558111 ssl_options.tls_intolerance_type =
8112 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8113
8114 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428115 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558116}
8117#endif // !OS_ANDROID
8118
[email protected]12833302014-07-02 01:57:318119// Tests that we don't fallback on handshake failure with servers that implement
8120// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558121TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558122 SpawnedTestServer::SSLOptions ssl_options(
8123 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438124 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558125 // a version fallback.
8126 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438127 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558128 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8129 // connections are rejected.
8130 ssl_options.fallback_scsv_enabled = true;
8131
8132 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8133
8134 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8135 // intolerance. If the fallback SCSV is processed when the original error
8136 // that caused the fallback should be returned, which should be
8137 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8138 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8139}
8140
[email protected]12833302014-07-02 01:57:318141// Tests that we don't fallback on connection closed with servers that implement
8142// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318143TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318144 SpawnedTestServer::SSLOptions ssl_options(
8145 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438146 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318147 // a version fallback.
8148 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438149 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318150 ssl_options.tls_intolerance_type =
8151 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8152 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8153 // connections are rejected.
8154 ssl_options.fallback_scsv_enabled = true;
8155
8156 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8157
8158 // The original error should be replayed on rejected fallback.
8159 ExpectFailure(ERR_CONNECTION_CLOSED);
8160}
8161
davidbenb937d6c2015-05-14 04:53:428162// Test that fallback probe connections don't cause sessions to be cached.
8163TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008164 SpawnedTestServer::SSLOptions ssl_options(
8165 SpawnedTestServer::SSLOptions::CERT_OK);
8166 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428167 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008168 ssl_options.tls_intolerance_type =
8169 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8170 ssl_options.record_resume = true;
8171
8172 SpawnedTestServer test_server(
8173 SpawnedTestServer::TYPE_HTTPS,
8174 ssl_options,
8175 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8176 ASSERT_TRUE(test_server.Start());
8177
8178 SSLClientSocket::ClearSessionCache();
8179
davidbenb937d6c2015-05-14 04:53:428180 // Make a connection that does a probe fallback to TLSv1 but fails because
8181 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008182 // be inserted locally.
8183 {
8184 TestDelegate delegate;
8185 FallbackTestURLRequestContext context(true);
8186
davidbenb937d6c2015-05-14 04:53:428187 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008188 context.Init();
8189 scoped_ptr<URLRequest> request(context.CreateRequest(
davidben151423e2015-03-23 18:48:368190 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008191 request->Start();
8192
8193 base::RunLoop().Run();
8194
8195 EXPECT_EQ(1, delegate.response_started_count());
8196 EXPECT_FALSE(request->status().is_success());
8197 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8198 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8199 request->status().error());
8200 }
8201
davidbenb937d6c2015-05-14 04:53:428202 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008203 {
8204 TestDelegate delegate;
8205 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428206 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008207
8208 context.Init();
davidben151423e2015-03-23 18:48:368209 scoped_ptr<URLRequest> request(context.CreateRequest(
8210 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008211 request->Start();
8212
8213 base::RunLoop().Run();
8214
8215 EXPECT_EQ(1, delegate.response_started_count());
8216 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428217 EXPECT_EQ(
8218 SSL_CONNECTION_VERSION_TLS1,
8219 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008220 EXPECT_TRUE(request->ssl_info().connection_status &
8221 SSL_CONNECTION_VERSION_FALLBACK);
8222
8223 std::vector<std::string> lines;
8224 // If no sessions were cached then the server should have seen two sessions
8225 // inserted with no lookups.
8226 AssertTwoDistinctSessionsInserted(delegate.data_received());
8227 }
8228}
8229
[email protected]a8fed1742013-12-27 02:14:248230class HTTPSSessionTest : public testing::Test {
8231 public:
8232 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598233 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248234
8235 default_context_.set_network_delegate(&default_network_delegate_);
8236 default_context_.set_cert_verifier(&cert_verifier_);
8237 default_context_.Init();
8238 }
dcheng67be2b1f2014-10-27 21:47:298239 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248240
8241 protected:
8242 MockCertVerifier cert_verifier_;
8243 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8244 TestURLRequestContext default_context_;
8245};
8246
8247// Tests that session resumption is not attempted if an invalid certificate
8248// is presented.
8249TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8250 SpawnedTestServer::SSLOptions ssl_options;
8251 ssl_options.record_resume = true;
8252 SpawnedTestServer test_server(
8253 SpawnedTestServer::TYPE_HTTPS,
8254 ssl_options,
8255 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8256 ASSERT_TRUE(test_server.Start());
8257
8258 SSLClientSocket::ClearSessionCache();
8259
8260 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598261 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248262 {
8263 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198264 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368265 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248266
[email protected]f7022f32014-08-21 16:32:198267 r->Start();
8268 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248269
8270 base::RunLoop().Run();
8271
8272 EXPECT_EQ(1, d.response_started_count());
8273 }
8274
8275 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8276 CloseAllConnections();
8277
8278 // Now change the certificate to be acceptable (so that the response is
8279 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598280 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248281 {
8282 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198283 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368284 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248285
[email protected]f7022f32014-08-21 16:32:198286 r->Start();
8287 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248288
8289 base::RunLoop().Run();
8290
8291 // The response will look like;
8292 // insert abc
8293 // insert xyz
8294 //
8295 // With a newline at the end which makes the split think that there are
8296 // three lines.
8297 //
8298 // If a session was presented (eg: a bug), then the response would look
8299 // like;
8300 // insert abc
8301 // lookup abc
8302 // insert xyz
8303
8304 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008305 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248306 }
8307}
8308
[email protected]dffe8242012-03-20 15:14:278309// This the fingerprint of the "Testing CA" certificate used by the testserver.
8310// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268311static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278312 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8313 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8314
[email protected]51523f52013-07-31 21:57:288315// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8316// testserver.
8317static const SHA256HashValue kOCSPTestCertSPKI = { {
8318 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8319 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8320 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8321 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8322} };
8323
[email protected]dffe8242012-03-20 15:14:278324// This is the policy OID contained in the certificates that testserver
8325// generates.
8326static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8327
8328class HTTPSOCSPTest : public HTTPSRequestTest {
8329 public:
8330 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098331 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088332 ev_test_policy_(
8333 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8334 kOCSPTestCertFingerprint,
8335 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028336 }
8337
dcheng67be2b1f2014-10-27 21:47:298338 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098339 SetupContext(&context_);
8340 context_.Init();
[email protected]dffe8242012-03-20 15:14:278341
[email protected]cba24642014-08-15 20:49:598342 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208343 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428344 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508345 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278346
davidben71f35ff2015-04-17 20:54:488347#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098348 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278349 EnsureNSSHttpIOInit();
8350#endif
8351 }
8352
[email protected]ce7d0cbc2013-05-03 18:57:228353 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278354 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538355 // We always overwrite out_cert_status.
8356 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228357 SpawnedTestServer test_server(
8358 SpawnedTestServer::TYPE_HTTPS,
8359 ssl_options,
8360 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278361 ASSERT_TRUE(test_server.Start());
8362
8363 TestDelegate d;
8364 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:198365 scoped_ptr<URLRequest> r(context_.CreateRequest(
davidben151423e2015-03-23 18:48:368366 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198367 r->Start();
[email protected]dffe8242012-03-20 15:14:278368
[email protected]255620da2013-08-19 13:14:298369 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278370
8371 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198372 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278373 }
8374
dcheng67be2b1f2014-10-27 21:47:298375 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488376#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278377 ShutdownNSSHttpIO();
8378#endif
8379 }
8380
[email protected]a13234c2012-03-20 21:45:028381 protected:
8382 // SetupContext configures the URLRequestContext that will be used for making
8383 // connetions to testserver. This can be overridden in test subclasses for
8384 // different behaviour.
8385 virtual void SetupContext(URLRequestContext* context) {
8386 context->set_ssl_config_service(
8387 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208388 true /* online revocation checking */,
8389 false /* require rev. checking for local
8390 anchors */));
[email protected]a13234c2012-03-20 21:45:028391 }
8392
[email protected]dffe8242012-03-20 15:14:278393 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098394 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088395 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278396};
8397
[email protected]a13234c2012-03-20 21:45:028398static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018399#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028400 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8401 // have that ability on other platforms.
8402 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8403#else
8404 return 0;
8405#endif
8406}
8407
[email protected]3a86a712013-07-30 07:16:208408// SystemSupportsHardFailRevocationChecking returns true iff the current
8409// operating system supports revocation checking and can distinguish between
8410// situations where a given certificate lacks any revocation information (eg:
8411// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8412// revocation information cannot be obtained (eg: the CRL was unreachable).
8413// If it does not, then tests which rely on 'hard fail' behaviour should be
8414// skipped.
8415static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:488416#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:208417 return true;
8418#else
8419 return false;
8420#endif
8421}
8422
[email protected]a13234c2012-03-20 21:45:028423// SystemUsesChromiumEVMetadata returns true iff the current operating system
8424// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8425// several tests are effected because our testing EV certificate won't be
8426// recognised as EV.
8427static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328428#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578429 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8430 return false;
[email protected]e1b2d732014-03-28 16:20:328431#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8432 // On OS X and Android, we use the system to tell us whether a certificate is
8433 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018434 return false;
8435#else
8436 return true;
8437#endif
8438}
8439
[email protected]b6f2de32012-08-17 04:35:088440static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008441#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578442 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8443 return false;
8444#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028445 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8446#elif defined(OS_ANDROID)
8447 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8448 return false;
8449#else
8450 return true;
8451#endif
8452}
8453
davidbend1fb2f12014-11-08 02:51:008454static bool SystemSupportsOCSPStapling() {
davidben71f35ff2015-04-17 20:54:488455#if defined(USE_NSS_CERTS)
davidbend1fb2f12014-11-08 02:51:008456 return true;
8457#elif defined(OS_WIN)
8458 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8459#else
8460 return false;
8461#endif
8462}
8463
[email protected]dffe8242012-03-20 15:14:278464TEST_F(HTTPSOCSPTest, Valid) {
8465 if (!SystemSupportsOCSP()) {
8466 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8467 return;
8468 }
8469
[email protected]ce7d0cbc2013-05-03 18:57:228470 SpawnedTestServer::SSLOptions ssl_options(
8471 SpawnedTestServer::SSLOptions::CERT_AUTO);
8472 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278473
[email protected]924e9f92012-12-16 22:00:538474 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128475 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278476
8477 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8478
[email protected]a13234c2012-03-20 21:45:028479 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8480 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278481
8482 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8483}
8484
8485TEST_F(HTTPSOCSPTest, Revoked) {
8486 if (!SystemSupportsOCSP()) {
8487 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8488 return;
8489 }
8490
[email protected]ce7d0cbc2013-05-03 18:57:228491 SpawnedTestServer::SSLOptions ssl_options(
8492 SpawnedTestServer::SSLOptions::CERT_AUTO);
8493 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278494
8495 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128496 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278497
[email protected]a592c0432012-12-01 18:10:298498#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278499 // Doesn't pass on OS X yet for reasons that need to be investigated.
8500 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8501#endif
8502 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8503 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8504}
8505
8506TEST_F(HTTPSOCSPTest, Invalid) {
8507 if (!SystemSupportsOCSP()) {
8508 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8509 return;
8510 }
8511
[email protected]ce7d0cbc2013-05-03 18:57:228512 SpawnedTestServer::SSLOptions ssl_options(
8513 SpawnedTestServer::SSLOptions::CERT_AUTO);
8514 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:278515
[email protected]924e9f92012-12-16 22:00:538516 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128517 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278518
[email protected]a13234c2012-03-20 21:45:028519 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278520 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:278521
8522 // Without a positive OCSP response, we shouldn't show the EV status.
8523 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8524 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8525}
[email protected]a13234c2012-03-20 21:45:028526
davidbend1fb2f12014-11-08 02:51:008527TEST_F(HTTPSOCSPTest, ValidStapled) {
8528 if (!SystemSupportsOCSPStapling()) {
8529 LOG(WARNING)
8530 << "Skipping test because system doesn't support OCSP stapling";
8531 return;
8532 }
8533
8534 SpawnedTestServer::SSLOptions ssl_options(
8535 SpawnedTestServer::SSLOptions::CERT_AUTO);
8536 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8537 ssl_options.staple_ocsp_response = true;
8538 ssl_options.ocsp_server_unavailable = true;
8539
8540 CertStatus cert_status;
8541 DoConnection(ssl_options, &cert_status);
8542
8543 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8544
8545 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8546 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8547
8548 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8549}
8550
davidben6c3191b2014-11-21 22:38:048551// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:488552#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:048553#define MAYBE_RevokedStapled DISABLED_RevokedStapled
8554#else
8555#define MAYBE_RevokedStapled RevokedStapled
8556#endif
8557TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
davidbend1fb2f12014-11-08 02:51:008558 if (!SystemSupportsOCSPStapling()) {
8559 LOG(WARNING)
8560 << "Skipping test because system doesn't support OCSP stapling";
8561 return;
8562 }
8563
8564 SpawnedTestServer::SSLOptions ssl_options(
8565 SpawnedTestServer::SSLOptions::CERT_AUTO);
8566 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8567 ssl_options.staple_ocsp_response = true;
8568 ssl_options.ocsp_server_unavailable = true;
8569
8570 CertStatus cert_status;
8571 DoConnection(ssl_options, &cert_status);
8572
8573 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8574 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8575 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8576}
8577
[email protected]3a86a712013-07-30 07:16:208578class HTTPSHardFailTest : public HTTPSOCSPTest {
8579 protected:
dchengb03027d2014-10-21 12:00:208580 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:208581 context->set_ssl_config_service(
8582 new TestSSLConfigService(false /* check for EV */,
8583 false /* online revocation checking */,
8584 true /* require rev. checking for local
8585 anchors */));
8586 }
8587};
8588
[email protected]3a86a712013-07-30 07:16:208589TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8590 if (!SystemSupportsOCSP()) {
8591 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8592 return;
8593 }
8594
8595 if (!SystemSupportsHardFailRevocationChecking()) {
8596 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8597 << "revocation checking";
8598 return;
8599 }
8600
8601 SpawnedTestServer::SSLOptions ssl_options(
8602 SpawnedTestServer::SSLOptions::CERT_AUTO);
8603 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8604
8605 CertStatus cert_status;
8606 DoConnection(ssl_options, &cert_status);
8607
8608 EXPECT_EQ(CERT_STATUS_REVOKED,
8609 cert_status & CERT_STATUS_REVOKED);
8610
8611 // Without a positive OCSP response, we shouldn't show the EV status.
8612 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8613}
8614
[email protected]a13234c2012-03-20 21:45:028615class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8616 protected:
dchengb03027d2014-10-21 12:00:208617 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028618 context->set_ssl_config_service(
8619 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208620 false /* online revocation checking */,
8621 false /* require rev. checking for local
8622 anchors */));
[email protected]a13234c2012-03-20 21:45:028623 }
8624};
8625
8626TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8627 if (!SystemSupportsOCSP()) {
8628 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8629 return;
8630 }
8631
[email protected]ce7d0cbc2013-05-03 18:57:228632 SpawnedTestServer::SSLOptions ssl_options(
8633 SpawnedTestServer::SSLOptions::CERT_AUTO);
8634 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028635 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8636
[email protected]924e9f92012-12-16 22:00:538637 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128638 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028639
8640 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8641 cert_status & CERT_STATUS_ALL_ERRORS);
8642
8643 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088644 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8645 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028646}
8647
[email protected]be0fff62013-08-29 23:37:488648TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8649 if (!SystemSupportsOCSP()) {
8650 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8651 return;
8652 }
8653
8654 SpawnedTestServer::SSLOptions ssl_options(
8655 SpawnedTestServer::SSLOptions::CERT_AUTO);
8656 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8657 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8658
8659 CertStatus cert_status;
8660 DoConnection(ssl_options, &cert_status);
8661
8662 // Currently only works for Windows. When using NSS or OS X, it's not
8663 // possible to determine whether the check failed because of actual
8664 // revocation or because there was an OCSP failure.
8665#if defined(OS_WIN)
8666 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8667#else
8668 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8669#endif
8670
8671 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8672 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8673 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8674}
8675
[email protected]a13234c2012-03-20 21:45:028676TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8677 if (!SystemSupportsOCSP()) {
8678 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8679 return;
8680 }
8681
[email protected]ce7d0cbc2013-05-03 18:57:228682 SpawnedTestServer::SSLOptions ssl_options(
8683 SpawnedTestServer::SSLOptions::CERT_AUTO);
8684 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:028685 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8686
8687 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128688 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028689
8690 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8691
8692 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8693 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:088694 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8695 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028696}
8697
8698TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8699 if (!SystemSupportsOCSP()) {
8700 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8701 return;
8702 }
8703
[email protected]ce7d0cbc2013-05-03 18:57:228704 SpawnedTestServer::SSLOptions ssl_options(
8705 SpawnedTestServer::SSLOptions::CERT_AUTO);
8706 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028707 SSLConfigService::SetCRLSet(
8708 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8709
8710 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128711 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028712
8713 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8714 cert_status & CERT_STATUS_ALL_ERRORS);
8715
8716 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088717 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8718 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028719}
8720
[email protected]51523f52013-07-31 21:57:288721TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8722 if (!SystemSupportsOCSP()) {
8723 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8724 return;
8725 }
8726
8727 SpawnedTestServer::SSLOptions ssl_options(
8728 SpawnedTestServer::SSLOptions::CERT_AUTO);
8729 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8730 SSLConfigService::SetCRLSet(
8731 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8732 false, &kOCSPTestCertSPKI, "")));
8733
8734 CertStatus cert_status;
8735 DoConnection(ssl_options, &cert_status);
8736
8737 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8738 // revocation check for EV.
8739 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8740 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8741 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8742 EXPECT_FALSE(
8743 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8744}
8745
8746TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8747 if (!SystemSupportsOCSP()) {
8748 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8749 return;
8750 }
8751
[email protected]ce7d0cbc2013-05-03 18:57:228752 SpawnedTestServer::SSLOptions ssl_options(
8753 SpawnedTestServer::SSLOptions::CERT_AUTO);
8754 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028755 SSLConfigService::SetCRLSet(
8756 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8757
[email protected]51523f52013-07-31 21:57:288758 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:128759 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028760
[email protected]51523f52013-07-31 21:57:288761 // Even with a fresh CRLSet, we should still do online revocation checks when
8762 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8763 // test.
8764 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8765 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:028766
[email protected]51523f52013-07-31 21:57:288767 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:028768 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:288769 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028770}
8771
[email protected]b6f2de32012-08-17 04:35:088772TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8773 // Test that when EV verification is requested, but online revocation
8774 // checking is disabled, and the leaf certificate is not in fact EV, that
8775 // no revocation checking actually happens.
8776 if (!SystemSupportsOCSP()) {
8777 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8778 return;
8779 }
8780
8781 // Unmark the certificate's OID as EV, which should disable revocation
8782 // checking (as per the user preference)
8783 ev_test_policy_.reset();
8784
[email protected]ce7d0cbc2013-05-03 18:57:228785 SpawnedTestServer::SSLOptions ssl_options(
8786 SpawnedTestServer::SSLOptions::CERT_AUTO);
8787 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:088788 SSLConfigService::SetCRLSet(
8789 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8790
8791 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128792 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:088793
8794 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8795
8796 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8797 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8798}
8799
[email protected]a13234c2012-03-20 21:45:028800class HTTPSCRLSetTest : public HTTPSOCSPTest {
8801 protected:
dchengb03027d2014-10-21 12:00:208802 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028803 context->set_ssl_config_service(
8804 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208805 false /* online revocation checking */,
8806 false /* require rev. checking for local
8807 anchors */));
[email protected]a13234c2012-03-20 21:45:028808 }
8809};
8810
8811TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:228812 SpawnedTestServer::SSLOptions ssl_options(
8813 SpawnedTestServer::SSLOptions::CERT_AUTO);
8814 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028815 SSLConfigService::SetCRLSet(
8816 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8817
[email protected]924e9f92012-12-16 22:00:538818 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128819 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028820
8821 // If we're not trying EV verification then, even if the CRLSet has expired,
8822 // we don't fall back to online revocation checks.
8823 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8824 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8825 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8826}
[email protected]51523f52013-07-31 21:57:288827
8828TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:308829#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:288830 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8831 return;
8832#endif
8833
8834 SpawnedTestServer::SSLOptions ssl_options(
8835 SpawnedTestServer::SSLOptions::CERT_AUTO);
8836 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8837 ssl_options.cert_serial = 10;
8838 SSLConfigService::SetCRLSet(
8839 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8840 false, &kOCSPTestCertSPKI, "\x0a")));
8841
8842 CertStatus cert_status = 0;
8843 DoConnection(ssl_options, &cert_status);
8844
8845 // If the certificate is recorded as revoked in the CRLSet, that should be
8846 // reflected without online revocation checking.
8847 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8848 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8849 EXPECT_FALSE(
8850 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8851}
[email protected]316c1e5e2012-09-12 15:17:448852#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278853
mmenke9f2ec60c2015-06-01 20:59:478854#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
8855// These tests aren't passing on Android. Either the RemoteTestServer isn't
8856// starting up successfully, or it can't access the test files.
8857// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:318858class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:118859 public:
[email protected]d9fca99a2012-02-24 16:16:208860 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:478861 : ftp_transaction_factory_(&host_resolver_),
8862 test_server_(SpawnedTestServer::TYPE_FTP,
8863 SpawnedTestServer::kLocalhost,
8864 base::FilePath(kTestFilePath)) {
8865 // Can't use |default_context_|'s HostResolver to set up the
8866 // FTPTransactionFactory because it hasn't been created yet.
8867 default_context_.set_host_resolver(&host_resolver_);
8868 }
8869
8870 // URLRequestTest interface:
8871 void SetUpFactory() override {
8872 // Add FTP support to the default URLRequestContext.
8873 job_factory_impl_->SetProtocolHandler(
8874 "ftp", new FtpProtocolHandler(&ftp_transaction_factory_));
8875 }
8876
8877 std::string GetTestFileContents() {
8878 base::FilePath path;
8879 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
8880 path = path.Append(kTestFilePath);
8881 path = path.AppendASCII(kFtpTestFile);
8882 std::string contents;
8883 EXPECT_TRUE(base::ReadFileToString(path, &contents));
8884 return contents;
[email protected]95409e12010-08-17 20:07:118885 }
8886
[email protected]b89ca032009-08-31 21:41:318887 protected:
mmenke9f2ec60c2015-06-01 20:59:478888 MockHostResolver host_resolver_;
8889 FtpNetworkLayer ftp_transaction_factory_;
8890
[email protected]ce7d0cbc2013-05-03 18:57:228891 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:318892};
8893
[email protected]d2a133182012-08-05 16:44:088894// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:098895TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:088896 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:088897
8898 TestDelegate d;
8899 {
davidben151423e2015-03-23 18:48:368900 scoped_ptr<URLRequest> r(
8901 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198902 r->Start();
8903 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:088904
[email protected]255620da2013-08-19 13:14:298905 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:088906
[email protected]f7022f32014-08-21 16:32:198907 EXPECT_FALSE(r->is_pending());
8908 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8909 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:088910 }
8911}
8912
mmenke9f2ec60c2015-06-01 20:59:478913TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:118914 ASSERT_TRUE(test_server_.Start());
8915
[email protected]a25e90e2009-09-09 17:05:378916 TestDelegate d;
8917 {
[email protected]f7022f32014-08-21 16:32:198918 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368919 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198920 r->Start();
8921 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378922
[email protected]255620da2013-08-19 13:14:298923 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:378924
[email protected]f7022f32014-08-21 16:32:198925 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378926 EXPECT_EQ(1, d.response_started_count());
8927 EXPECT_FALSE(d.received_data_before_response());
8928 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:198929 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198930 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198931 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198932 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:378933 }
8934}
8935
mmenke9f2ec60c2015-06-01 20:59:478936TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:118937 ASSERT_TRUE(test_server_.Start());
8938
[email protected]dd265012009-01-08 20:45:278939 TestDelegate d;
8940 {
[email protected]f7022f32014-08-21 16:32:198941 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:478942 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198943 r->Start();
8944 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278945
[email protected]255620da2013-08-19 13:14:298946 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278947
[email protected]f7022f32014-08-21 16:32:198948 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278949 EXPECT_EQ(1, d.response_started_count());
8950 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:478951 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:198952 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198953 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198954 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198955 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278956 }
8957}
8958
mmenke9f2ec60c2015-06-01 20:59:478959TEST_F(URLRequestTestFTP, FTPGetTest) {
[email protected]95409e12010-08-17 20:07:118960 ASSERT_TRUE(test_server_.Start());
8961
[email protected]dd265012009-01-08 20:45:278962 TestDelegate d;
8963 {
mmenke9f2ec60c2015-06-01 20:59:478964 scoped_ptr<URLRequest> r(
8965 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
8966 kFtpTestFile, "chrome", "chrome"),
8967 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198968 r->Start();
8969 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278970
[email protected]255620da2013-08-19 13:14:298971 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278972
[email protected]f7022f32014-08-21 16:32:198973 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:478974 EXPECT_EQ(1, d.response_started_count());
8975 EXPECT_FALSE(d.received_data_before_response());
8976 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:198977 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198978 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198979 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198980 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:258981
8982 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198983 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258984 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:278985 }
8986}
8987
mmenke9f2ec60c2015-06-01 20:59:478988TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:118989 ASSERT_TRUE(test_server_.Start());
8990
[email protected]dd265012009-01-08 20:45:278991 TestDelegate d;
8992 {
[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]dd265012009-01-08 20:45:278999
[email protected]255620da2013-08-19 13:14:299000 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279001
[email protected]f7022f32014-08-21 16:32:199002 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279003 EXPECT_EQ(1, d.response_started_count());
9004 EXPECT_FALSE(d.received_data_before_response());
9005 EXPECT_EQ(d.bytes_received(), 0);
9006 }
9007}
9008
mmenke9f2ec60c2015-06-01 20:59:479009TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:119010 ASSERT_TRUE(test_server_.Start());
9011
[email protected]8b8a197d2009-08-26 15:57:589012 TestDelegate d;
9013 // Set correct login credentials. The delegate will be asked for them when
9014 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589015 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589016 {
[email protected]f7022f32014-08-21 16:32:199017 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479018 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199019 "wrong_password"),
davidben151423e2015-03-23 18:48:369020 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199021 r->Start();
9022 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589023
[email protected]255620da2013-08-19 13:14:299024 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589025
[email protected]f7022f32014-08-21 16:32:199026 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589027 EXPECT_EQ(1, d.response_started_count());
9028 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479029 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589030 }
9031}
9032
mmenke9f2ec60c2015-06-01 20:59:479033TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:119034 ASSERT_TRUE(test_server_.Start());
9035
[email protected]dd265012009-01-08 20:45:279036 TestDelegate d;
9037 {
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]dd265012009-01-08 20:45:279044
[email protected]255620da2013-08-19 13:14:299045 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279046
[email protected]f7022f32014-08-21 16:32:199047 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279048 EXPECT_EQ(1, d.response_started_count());
9049 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479050 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279051 }
9052}
[email protected]8b8a197d2009-08-26 15:57:589053
mmenke9f2ec60c2015-06-01 20:59:479054TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:119055 ASSERT_TRUE(test_server_.Start());
9056
[email protected]8b8a197d2009-08-26 15:57:589057 TestDelegate d;
9058 // Set correct login credentials. The delegate will be asked for them when
9059 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589060 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589061 {
mmenke9f2ec60c2015-06-01 20:59:479062 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9063 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9064 "chrome"),
9065 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199066 r->Start();
9067 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589068
[email protected]255620da2013-08-19 13:14:299069 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589070
[email protected]f7022f32014-08-21 16:32:199071 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589072 EXPECT_EQ(1, d.response_started_count());
9073 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479074 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589075 }
9076}
[email protected]60a3df52009-09-22 16:13:249077
mmenke9f2ec60c2015-06-01 20:59:479078TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:119079 ASSERT_TRUE(test_server_.Start());
9080
[email protected]60a3df52009-09-22 16:13:249081 scoped_ptr<TestDelegate> d(new TestDelegate);
9082 {
9083 // Pass correct login identity in the URL.
mmenke9f2ec60c2015-06-01 20:59:479084 scoped_ptr<URLRequest> r(
9085 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9086 kFtpTestFile, "chrome", "chrome"),
9087 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199088 r->Start();
9089 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249090
[email protected]255620da2013-08-19 13:14:299091 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249092
[email protected]f7022f32014-08-21 16:32:199093 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249094 EXPECT_EQ(1, d->response_started_count());
9095 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479096 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249097 }
9098
9099 d.reset(new TestDelegate);
9100 {
9101 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199102 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479103 test_server_.GetURL(kFtpTestFile), 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
mmenke9f2ec60c2015-06-01 20:59:479116TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:119117 ASSERT_TRUE(test_server_.Start());
9118
[email protected]60a3df52009-09-22 16:13:249119 scoped_ptr<TestDelegate> d(new TestDelegate);
9120 // Set correct login credentials. The delegate will be asked for them when
9121 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589122 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249123 {
[email protected]f7022f32014-08-21 16:32:199124 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479125 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199126 "wrong_password"),
davidben151423e2015-03-23 18:48:369127 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199128 r->Start();
9129 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249130
[email protected]255620da2013-08-19 13:14:299131 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249132
[email protected]f7022f32014-08-21 16:32:199133 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249134 EXPECT_EQ(1, d->response_started_count());
9135 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479136 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249137 }
9138
9139 // Use a new delegate without explicit credentials. The cached ones should be
9140 // used.
9141 d.reset(new TestDelegate);
9142 {
9143 // Don't pass wrong credentials in the URL, they would override valid cached
9144 // ones.
[email protected]f7022f32014-08-21 16:32:199145 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479146 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199147 r->Start();
9148 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249149
[email protected]255620da2013-08-19 13:14:299150 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249151
[email protected]f7022f32014-08-21 16:32:199152 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249153 EXPECT_EQ(1, d->response_started_count());
9154 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479155 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249156 }
9157}
[email protected]316c1e5e2012-09-12 15:17:449158#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519159
ttuttlec0c828492015-05-15 01:25:559160TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9161 TestDelegate d;
9162 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9163 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9164 d.set_quit_on_network_start(true);
9165
9166 EXPECT_FALSE(req->response_info().network_accessed);
9167
9168 req->Start();
9169 base::RunLoop().Run();
9170
9171 EXPECT_EQ(1, d.received_before_network_start_count());
9172 EXPECT_EQ(0, d.response_started_count());
9173 EXPECT_FALSE(req->response_info().network_accessed);
9174
9175 req->ResumeNetworkStart();
9176 base::RunLoop().Run();
9177}
9178
9179TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9180 TestDelegate d;
9181 scoped_ptr<URLRequest> req(
9182 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9183
9184 EXPECT_FALSE(req->response_info().network_accessed);
9185
9186 req->Start();
9187 base::RunLoop().Run();
9188
9189 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9190 EXPECT_FALSE(req->response_info().network_accessed);
9191}
9192
9193TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9194 MockHostResolver host_resolver;
9195 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9196 TestURLRequestContext context(true);
9197 context.set_network_delegate(&network_delegate);
9198 context.set_host_resolver(&host_resolver);
9199 host_resolver.rules()->AddSimulatedFailure("*");
9200 context.Init();
9201
9202 TestDelegate d;
9203 scoped_ptr<URLRequest> req(context.CreateRequest(
9204 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9205
9206 EXPECT_FALSE(req->response_info().network_accessed);
9207
9208 req->Start();
9209 base::RunLoop().Run();
9210 EXPECT_TRUE(req->response_info().network_accessed);
9211}
9212
[email protected]7461a402011-03-24 23:19:519213} // namespace net