blob: 530c3e6e117e793ac3ca58f1cbe9783d40f1aa0a [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"
estark06e0dac2015-08-07 21:56:0123#include "base/json/json_reader.h"
skyostil4891b25b2015-06-11 11:43:4524#include "base/location.h"
mmenke19378d22014-09-09 04:12:5925#include "base/memory/scoped_ptr.h"
[email protected]084262c2011-12-01 21:12:4726#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2227#include "base/message_loop/message_loop.h"
initial.commit586acc5fe2008-07-26 22:42:5228#include "base/path_service.h"
mmenkefb18c772015-09-30 22:22:5029#include "base/power_monitor/power_monitor.h"
30#include "base/power_monitor/power_monitor_source.h"
[email protected]255620da2013-08-19 13:14:2931#include "base/run_loop.h"
skyostil4891b25b2015-06-11 11:43:4532#include "base/single_thread_task_runner.h"
[email protected]4dc3ad4f2013-06-11 07:15:5033#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5534#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2235#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2236#include "base/strings/string_util.h"
37#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0538#include "base/strings/utf_string_conversions.h"
tbansalea2fb8c2015-05-22 22:23:0039#include "base/test/histogram_tester.h"
skyostil4891b25b2015-06-11 11:43:4540#include "base/thread_task_runner_handle.h"
estark06e0dac2015-08-07 21:56:0141#include "base/values.h"
mmenkecbc2b712014-10-09 20:29:0742#include "net/base/chunked_upload_data_stream.h"
43#include "net/base/elements_upload_data_stream.h"
tbansal1c92d5b2015-08-14 20:14:4344#include "net/base/external_estimate_provider.h"
initial.commit586acc5fe2008-07-26 22:42:5245#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2546#include "net/base/load_timing_info.h"
47#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0648#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5249#include "net/base/net_module.h"
50#include "net/base/net_util.h"
tbansalea2fb8c2015-05-22 22:23:0051#include "net/base/network_quality_estimator.h"
[email protected]2ca01e52013-10-31 22:05:1952#include "net/base/request_priority.h"
[email protected]42fdb452012-11-01 12:44:4053#include "net/base/test_data_directory.h"
[email protected]f288ef02012-12-15 20:28:2854#include "net/base/upload_bytes_element_reader.h"
55#include "net/base/upload_data_stream.h"
56#include "net/base/upload_file_element_reader.h"
[email protected]6e7845ae2013-03-29 21:48:1157#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2458#include "net/cert/mock_cert_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1159#include "net/cert/test_root_certs.h"
eromaned744f32015-04-09 06:35:4960#include "net/cert_net/nss_ocsp.h"
[email protected]aa84a7e2012-03-15 21:29:0661#include "net/cookies/cookie_monster.h"
62#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5263#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5364#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3865#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5266#include "net/http/http_cache.h"
67#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1968#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2569#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2170#include "net/http/http_response_headers.h"
[email protected]e50efea2014-03-24 18:41:0071#include "net/http/http_util.h"
eroman87c53d62015-04-02 06:51:0772#include "net/log/net_log.h"
vishal.b62985ca92015-04-17 08:45:5173#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4674#include "net/log/test_net_log_entry.h"
75#include "net/log/test_net_log_util.h"
[email protected]63de95b2008-12-10 04:11:2776#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1977#include "net/socket/ssl_client_socket.h"
davidben8ecc3072014-09-03 23:19:0978#include "net/ssl/ssl_cipher_suite_names.h"
[email protected]536fd0b2013-03-14 17:41:5779#include "net/ssl/ssl_connection_status_flags.h"
[email protected]6e7845ae2013-03-29 21:48:1180#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:3681#include "net/test/embedded_test_server/embedded_test_server.h"
82#include "net/test/embedded_test_server/http_request.h"
83#include "net/test/embedded_test_server/http_response.h"
[email protected]89b32522013-05-07 20:04:2184#include "net/test/spawned_test_server/spawned_test_server.h"
mmenkefb18c772015-09-30 22:22:5085#include "net/test/url_request/url_request_failed_job.h"
[email protected]e0f35c92013-05-08 16:04:3486#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4387#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5288#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:5089#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:1490#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:5091#include "net/url_request/url_request_intercepting_job_factory.h"
92#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:4993#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5194#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4795#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4496#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5297#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1598#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:5299
[email protected]02494ec2014-05-07 15:05:29100#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55101#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29102#include "net/url_request/file_protocol_handler.h"
103#include "net/url_request/url_request_file_dir_job.h"
104#endif
105
mmenke9f2ec60c2015-06-01 20:59:47106#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
107#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29108#include "net/url_request/ftp_protocol_handler.h"
109#endif
110
[email protected]dffe8242012-03-20 15:14:27111#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48112#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56113#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27114#include "base/win/windows_version.h"
115#endif
116
[email protected]ad65a3e2013-12-25 18:18:01117using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33118using base::Time;
halton.huoe4e45742014-12-08 07:55:46119using std::string;
[email protected]e1acf6f2008-10-27 20:43:33120
[email protected]7461a402011-03-24 23:19:51121namespace net {
122
initial.commit586acc5fe2008-07-26 22:42:52123namespace {
124
[email protected]42cba2fb2013-03-29 19:58:57125const base::string16 kChrome(ASCIIToUTF16("chrome"));
126const base::string16 kSecret(ASCIIToUTF16("secret"));
127const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44128
mmenke9f2ec60c2015-06-01 20:59:47129const base::FilePath::CharType kTestFilePath[] =
130 FILE_PATH_LITERAL("net/data/url_request_unittest");
131
132#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
133// Test file used in most FTP tests.
134const char kFtpTestFile[] = "BullRunSpeech.txt";
135#endif
136
[email protected]2bba3252013-04-08 19:50:59137// Tests load timing information in the case a fresh connection was used, with
138// no proxy.
[email protected]cba24642014-08-15 20:49:59139void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25140 int connect_timing_flags) {
141 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59142 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25143
144 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
145 EXPECT_FALSE(load_timing_info.request_start.is_null());
146
147 EXPECT_LE(load_timing_info.request_start,
148 load_timing_info.connect_timing.connect_start);
149 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
150 connect_timing_flags);
151 EXPECT_LE(load_timing_info.connect_timing.connect_end,
152 load_timing_info.send_start);
153 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
154 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
155
[email protected]58e32bb2013-01-21 18:23:25156 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
157 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
158}
159
[email protected]2bba3252013-04-08 19:50:59160// Same as above, but with proxy times.
161void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59162 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59163 int connect_timing_flags) {
164 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59165 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59166
167 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
168 EXPECT_FALSE(load_timing_info.request_start.is_null());
169
170 EXPECT_LE(load_timing_info.request_start,
171 load_timing_info.proxy_resolve_start);
172 EXPECT_LE(load_timing_info.proxy_resolve_start,
173 load_timing_info.proxy_resolve_end);
174 EXPECT_LE(load_timing_info.proxy_resolve_end,
175 load_timing_info.connect_timing.connect_start);
176 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
177 connect_timing_flags);
178 EXPECT_LE(load_timing_info.connect_timing.connect_end,
179 load_timing_info.send_start);
180 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
181 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
182}
183
184// Same as above, but with a reused socket and proxy times.
185void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59186 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59187 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59188 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59189
190 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
191 EXPECT_FALSE(load_timing_info.request_start.is_null());
192
193 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
194
195 EXPECT_LE(load_timing_info.request_start,
196 load_timing_info.proxy_resolve_start);
197 EXPECT_LE(load_timing_info.proxy_resolve_start,
198 load_timing_info.proxy_resolve_end);
199 EXPECT_LE(load_timing_info.proxy_resolve_end,
200 load_timing_info.send_start);
201 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
202 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
203}
204
xunjielia6888202015-04-14 21:34:25205#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25206// Tests load timing information in the case of a cache hit, when no cache
207// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17208base::StringPiece TestNetResourceProvider(int key) {
209 return "header";
210}
211
212void FillBuffer(char* buffer, size_t len) {
213 static bool called = false;
214 if (!called) {
215 called = true;
216 int seed = static_cast<int>(Time::Now().ToInternalValue());
217 srand(seed);
218 }
219
220 for (size_t i = 0; i < len; i++) {
221 buffer[i] = static_cast<char>(rand());
222 if (!buffer[i])
223 buffer[i] = 'g';
224 }
225}
xunjielia6888202015-04-14 21:34:25226#endif
[email protected]e3a85452013-11-14 01:46:17227
228#if !defined(OS_IOS)
[email protected]3b23a222013-05-15 21:33:25229void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59230 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25231 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59232 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25233
234 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
235 EXPECT_FALSE(load_timing_info.request_start.is_null());
236
237 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
238 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
239 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
240 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
241
242 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
243 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
244}
245
mmenke9f2ec60c2015-06-01 20:59:47246#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25247// Tests load timing in the case that there is no HTTP response. This can be
248// used to test in the case of errors or non-HTTP requests.
249void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59250 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25251 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59252 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25253
254 // Only the request times should be non-null.
255 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
256 EXPECT_FALSE(load_timing_info.request_start.is_null());
257
258 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
259
260 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
261 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
262 EXPECT_TRUE(load_timing_info.send_start.is_null());
263 EXPECT_TRUE(load_timing_info.send_end.is_null());
264 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
265}
xunjielia6888202015-04-14 21:34:25266#endif
[email protected]58e32bb2013-01-21 18:23:25267
mmenkefb18c772015-09-30 22:22:50268// Test power monitor source that can simulate entering suspend mode. Can't use
269// the one in base/ because it insists on bringing its own MessageLoop.
270class TestPowerMonitorSource : public base::PowerMonitorSource {
271 public:
272 TestPowerMonitorSource() {}
273 ~TestPowerMonitorSource() override {}
274
275 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
276
277 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
278
279 bool IsOnBatteryPowerImpl() override { return false; }
280
281 private:
282 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
283};
284
[email protected]71c64f62008-11-15 04:36:51285// Do a case-insensitive search through |haystack| for |needle|.
286bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50287 std::string::const_iterator it = std::search(
288 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
289 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51290 return it != haystack.end();
291}
292
mmenkecbc2b712014-10-09 20:29:07293scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
[email protected]f288ef02012-12-15 20:28:28294 scoped_ptr<UploadElementReader> reader(
295 new UploadBytesElementReader(data, strlen(data)));
mmenkecbc2b712014-10-09 20:29:07296 return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23297}
298
[email protected]96adadb2010-08-28 01:16:17299// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51300void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17301 // -1 means unknown. 0 means no encryption.
302 EXPECT_GT(ssl_info.security_bits, 0);
303
304 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
pkasting6b68a162014-12-01 22:10:29305 uint16 cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17306 ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29307 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17308}
309
[email protected]79e1fd62013-06-20 06:50:04310void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
311 const GURL& host_url) {
312 std::string sent_value;
313
314 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
315 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
316
317 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
318 EXPECT_EQ("keep-alive", sent_value);
319}
320
[email protected]ede03212012-09-07 12:52:26321bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27322 size_t size = a.size();
323
324 if (size != b.size())
325 return false;
326
327 for (size_t i = 0; i < size; ++i) {
328 if (!a[i].Equals(b[i]))
329 return false;
330 }
331
332 return true;
333}
[email protected]e3a85452013-11-14 01:46:17334#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27335
[email protected]dc5a5cf2012-09-26 02:49:30336// A network delegate that allows the user to choose a subset of request stages
337// to block in. When blocking, the delegate can do one of the following:
338// * synchronously return a pre-specified error code, or
339// * asynchronously return that value via an automatically called callback,
340// or
341// * block and wait for the user to do a callback.
342// Additionally, the user may also specify a redirect URL -- then each request
343// with the current URL different from the redirect target will be redirected
344// to that target, in the on-before-URL-request stage, independent of whether
345// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12346class BlockingNetworkDelegate : public TestNetworkDelegate {
347 public:
[email protected]dc5a5cf2012-09-26 02:49:30348 // Stages in which the delegate can block.
349 enum Stage {
[email protected]9045b8822012-01-13 20:35:35350 NOT_BLOCKED = 0,
351 ON_BEFORE_URL_REQUEST = 1 << 0,
352 ON_BEFORE_SEND_HEADERS = 1 << 1,
353 ON_HEADERS_RECEIVED = 1 << 2,
354 ON_AUTH_REQUIRED = 1 << 3
355 };
356
[email protected]dc5a5cf2012-09-26 02:49:30357 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59358 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30359 enum BlockMode {
360 SYNCHRONOUS, // No callback, returns specified return values.
361 AUTO_CALLBACK, // |this| posts a task to run the callback using the
362 // specified return codes.
363 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
364 // |auth_retval_| are ignored. In every blocking stage the
365 // message loop is quit.
366 };
367
368 // Creates a delegate which does not block at all.
369 explicit BlockingNetworkDelegate(BlockMode block_mode);
370
371 // For users to trigger a callback returning |response|.
372 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
373 // Only call if |block_mode_| == USER_CALLBACK.
374 void DoCallback(int response);
375 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
376
377 // Setters.
378 void set_retval(int retval) {
379 ASSERT_NE(USER_CALLBACK, block_mode_);
380 ASSERT_NE(ERR_IO_PENDING, retval);
381 ASSERT_NE(OK, retval);
382 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35383 }
384
[email protected]dc5a5cf2012-09-26 02:49:30385 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
386 // |auth_credentials_| will be passed with the response.
387 void set_auth_retval(AuthRequiredResponse auth_retval) {
388 ASSERT_NE(USER_CALLBACK, block_mode_);
389 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
390 auth_retval_ = auth_retval;
391 }
392 void set_auth_credentials(const AuthCredentials& auth_credentials) {
393 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35394 }
395
[email protected]dc5a5cf2012-09-26 02:49:30396 void set_redirect_url(const GURL& url) {
397 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35398 }
399
[email protected]dc5a5cf2012-09-26 02:49:30400 void set_block_on(int block_on) {
401 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35402 }
403
[email protected]dc5a5cf2012-09-26 02:49:30404 // Allows the user to check in which state did we block.
405 Stage stage_blocked_for_callback() const {
406 EXPECT_EQ(USER_CALLBACK, block_mode_);
407 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35408 }
409
410 private:
[email protected]dc5a5cf2012-09-26 02:49:30411 void RunCallback(int response, const CompletionCallback& callback);
412 void RunAuthCallback(AuthRequiredResponse response,
413 const AuthCallback& callback);
414
[email protected]9045b8822012-01-13 20:35:35415 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20416 int OnBeforeURLRequest(URLRequest* request,
417 const CompletionCallback& callback,
418 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35419
dchengb03027d2014-10-21 12:00:20420 int OnBeforeSendHeaders(URLRequest* request,
421 const CompletionCallback& callback,
422 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35423
dchengb03027d2014-10-21 12:00:20424 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35425 URLRequest* request,
426 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32427 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16428 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13429 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35430
dchengb03027d2014-10-21 12:00:20431 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35432 URLRequest* request,
433 const AuthChallengeInfo& auth_info,
434 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13435 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35436
[email protected]dc5a5cf2012-09-26 02:49:30437 // Resets the callbacks and |stage_blocked_for_callback_|.
438 void Reset();
[email protected]9045b8822012-01-13 20:35:35439
[email protected]dc5a5cf2012-09-26 02:49:30440 // Checks whether we should block in |stage|. If yes, returns an error code
441 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
442 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
443
444 // Configuration parameters, can be adjusted by public methods:
445 const BlockMode block_mode_;
446
447 // Values returned on blocking stages when mode is SYNCHRONOUS or
448 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
449 int retval_; // To be returned in non-auth stages.
450 AuthRequiredResponse auth_retval_;
451
[email protected]5f714132014-03-26 10:41:16452 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30453 int block_on_; // Bit mask: in which stages to block.
454
455 // |auth_credentials_| will be copied to |*target_auth_credential_| on
456 // callback.
457 AuthCredentials auth_credentials_;
458 AuthCredentials* target_auth_credentials_;
459
460 // Internal variables, not set by not the user:
461 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
462 // USER_CALLBACK).
463 Stage stage_blocked_for_callback_;
464
465 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35466 CompletionCallback callback_;
467 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30468
469 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
470
471 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35472};
473
[email protected]dc5a5cf2012-09-26 02:49:30474BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
475 : block_mode_(block_mode),
476 retval_(OK),
477 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
478 block_on_(0),
479 target_auth_credentials_(NULL),
480 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32481 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30482}
483
484void BlockingNetworkDelegate::DoCallback(int response) {
485 ASSERT_EQ(USER_CALLBACK, block_mode_);
486 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
487 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
488 CompletionCallback callback = callback_;
489 Reset();
490 RunCallback(response, callback);
491}
492
493void BlockingNetworkDelegate::DoAuthCallback(
494 NetworkDelegate::AuthRequiredResponse response) {
495 ASSERT_EQ(USER_CALLBACK, block_mode_);
496 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
497 AuthCallback auth_callback = auth_callback_;
498 Reset();
499 RunAuthCallback(response, auth_callback);
500}
501
502void BlockingNetworkDelegate::RunCallback(int response,
503 const CompletionCallback& callback) {
504 callback.Run(response);
505}
506
507void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
508 const AuthCallback& callback) {
509 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
510 ASSERT_TRUE(target_auth_credentials_ != NULL);
511 *target_auth_credentials_ = auth_credentials_;
512 }
513 callback.Run(response);
514}
515
516int BlockingNetworkDelegate::OnBeforeURLRequest(
517 URLRequest* request,
518 const CompletionCallback& callback,
519 GURL* new_url) {
520 if (redirect_url_ == request->url())
521 return OK; // We've already seen this request and redirected elsewhere.
522
523 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
524
525 if (!redirect_url_.is_empty())
526 *new_url = redirect_url_;
527
528 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
529}
530
531int BlockingNetworkDelegate::OnBeforeSendHeaders(
532 URLRequest* request,
533 const CompletionCallback& callback,
534 HttpRequestHeaders* headers) {
535 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
536
537 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
538}
539
540int BlockingNetworkDelegate::OnHeadersReceived(
541 URLRequest* request,
542 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32543 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16544 scoped_refptr<HttpResponseHeaders>* override_response_headers,
545 GURL* allowed_unsafe_redirect_url) {
546 TestNetworkDelegate::OnHeadersReceived(request,
547 callback,
548 original_response_headers,
549 override_response_headers,
550 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30551
552 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
553}
554
555NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
556 URLRequest* request,
557 const AuthChallengeInfo& auth_info,
558 const AuthCallback& callback,
559 AuthCredentials* credentials) {
560 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
561 credentials);
562 // Check that the user has provided callback for the previous blocked stage.
563 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
564
565 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
566 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
567 }
568
569 target_auth_credentials_ = credentials;
570
571 switch (block_mode_) {
572 case SYNCHRONOUS:
573 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
574 *target_auth_credentials_ = auth_credentials_;
575 return auth_retval_;
576
577 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45578 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30579 FROM_HERE,
580 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
581 weak_factory_.GetWeakPtr(), auth_retval_, callback));
582 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
583
584 case USER_CALLBACK:
585 auth_callback_ = callback;
586 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45587 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17588 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30589 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
590 }
591 NOTREACHED();
592 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
593}
594
595void BlockingNetworkDelegate::Reset() {
596 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
597 stage_blocked_for_callback_ = NOT_BLOCKED;
598 callback_.Reset();
599 auth_callback_.Reset();
600}
601
602int BlockingNetworkDelegate::MaybeBlockStage(
603 BlockingNetworkDelegate::Stage stage,
604 const CompletionCallback& callback) {
605 // Check that the user has provided callback for the previous blocked stage.
606 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
607
608 if ((block_on_ & stage) == 0) {
609 return OK;
610 }
611
612 switch (block_mode_) {
613 case SYNCHRONOUS:
614 EXPECT_NE(OK, retval_);
615 return retval_;
616
617 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45618 base::ThreadTaskRunnerHandle::Get()->PostTask(
619 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
620 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30621 return ERR_IO_PENDING;
622
623 case USER_CALLBACK:
624 callback_ = callback;
625 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45626 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17627 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30628 return ERR_IO_PENDING;
629 }
630 NOTREACHED();
631 return 0;
632}
633
[email protected]d5a4dd62012-05-23 01:41:04634class TestURLRequestContextWithProxy : public TestURLRequestContext {
635 public:
636 // Does not own |delegate|.
637 TestURLRequestContextWithProxy(const std::string& proxy,
638 NetworkDelegate* delegate)
639 : TestURLRequestContext(true) {
640 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
641 set_network_delegate(delegate);
642 Init();
643 }
dchengb03027d2014-10-21 12:00:20644 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04645};
646
estark06e0dac2015-08-07 21:56:01647// A mock ReportSender that just remembers the latest report
648// URI and report to be sent.
649class MockCertificateReportSender
650 : public TransportSecurityState::ReportSender {
651 public:
652 MockCertificateReportSender() {}
653 ~MockCertificateReportSender() override {}
654
655 void Send(const GURL& report_uri, const std::string& report) override {
656 latest_report_uri_ = report_uri;
657 latest_report_ = report;
658 }
659
660 const GURL& latest_report_uri() { return latest_report_uri_; }
661 const std::string& latest_report() { return latest_report_; }
662
663 private:
664 GURL latest_report_uri_;
665 std::string latest_report_;
666};
667
estarkcd39c11f2015-10-19 19:46:36668class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
669 public:
670 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
671};
672
[email protected]d5a4dd62012-05-23 01:41:04673} // namespace
674
[email protected]a592c0432012-12-01 18:10:29675// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48676class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00677 public:
[email protected]ef2bf422012-05-11 03:27:09678 URLRequestTest() : default_context_(true) {
679 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25680 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50681 job_factory_impl_ = new URLRequestJobFactoryImpl();
682 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50683 }
bengr1bf8e942014-11-07 01:36:50684
dcheng67be2b1f2014-10-27 21:47:29685 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18686 // URLRequestJobs may post clean-up tasks on destruction.
687 base::RunLoop().RunUntilIdle();
688 }
[email protected]87a09a92011-07-14 15:50:50689
dcheng2339883c2014-12-23 00:23:05690 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50691 SetUpFactory();
692 default_context_.set_job_factory(job_factory_.get());
693 default_context_.Init();
694 PlatformTest::SetUp();
695 }
696
697 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20698 job_factory_impl_->SetProtocolHandler(
699 "data", make_scoped_ptr(new DataProtocolHandler));
bengr1bf8e942014-11-07 01:36:50700#if !defined(DISABLE_FILE_SUPPORT)
701 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:20702 "file", make_scoped_ptr(new FileProtocolHandler(
703 base::ThreadTaskRunnerHandle::Get())));
bengr1bf8e942014-11-07 01:36:50704#endif
705 }
706
707 TestNetworkDelegate* default_network_delegate() {
708 return &default_network_delegate_;
709 }
710
711 const TestURLRequestContext& default_context() const {
712 return default_context_;
713 }
714
715
[email protected]3c5ca8c2011-09-29 01:14:51716 // Adds the TestJobInterceptor to the default context.
717 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23718 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20719 job_factory_impl_->SetProtocolHandler("http", nullptr);
720 job_factory_impl_->SetProtocolHandler("http",
721 make_scoped_ptr(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23722 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51723 }
724
[email protected]87a09a92011-07-14 15:50:50725 protected:
vishal.b62985ca92015-04-17 08:45:51726 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24727 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50728 URLRequestJobFactoryImpl* job_factory_impl_;
729 scoped_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09730 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48731};
732
[email protected]316c1e5e2012-09-12 15:17:44733TEST_F(URLRequestTest, AboutBlankTest) {
734 TestDelegate d;
735 {
[email protected]f7022f32014-08-21 16:32:19736 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36737 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44738
[email protected]f7022f32014-08-21 16:32:19739 r->Start();
740 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44741
[email protected]255620da2013-08-19 13:14:29742 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44743
[email protected]f7022f32014-08-21 16:32:19744 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44745 EXPECT_FALSE(d.received_data_before_response());
746 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19747 EXPECT_EQ("", r->GetSocketAddress().host());
748 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04749
750 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19751 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44752 }
753}
754
755TEST_F(URLRequestTest, DataURLImageTest) {
756 TestDelegate d;
757 {
758 // Use our nice little Chrome logo.
[email protected]f7022f32014-08-21 16:32:19759 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:19760 GURL(
davidben151423e2015-03-23 18:48:36761 "data:image/png;base64,"
762 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
763 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
764 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
765 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
766 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
767 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
768 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
769 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
770 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
771 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
772 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
773 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
774 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
775 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
776 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
777 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
778 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
779 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
780 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
781 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44782
[email protected]f7022f32014-08-21 16:32:19783 r->Start();
784 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44785
[email protected]255620da2013-08-19 13:14:29786 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44787
[email protected]f7022f32014-08-21 16:32:19788 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44789 EXPECT_FALSE(d.received_data_before_response());
790 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19791 EXPECT_EQ("", r->GetSocketAddress().host());
792 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04793
794 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19795 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44796 }
797}
798
[email protected]5ecf7cb282014-05-11 01:49:55799#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44800TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15801 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44802 PathService::Get(base::FILE_EXE, &app_path);
803 GURL app_url = FilePathToFileURL(app_path);
804
805 TestDelegate d;
806 {
davidben151423e2015-03-23 18:48:36807 scoped_ptr<URLRequest> r(
808 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44809
[email protected]f7022f32014-08-21 16:32:19810 r->Start();
811 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44812
[email protected]255620da2013-08-19 13:14:29813 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44814
815 int64 file_size = -1;
[email protected]56285702013-12-04 18:22:49816 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44817
[email protected]f7022f32014-08-21 16:32:19818 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44819 EXPECT_EQ(1, d.response_started_count());
820 EXPECT_FALSE(d.received_data_before_response());
821 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19822 EXPECT_EQ("", r->GetSocketAddress().host());
823 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04824
825 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19826 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44827 }
828}
829
[email protected]ba40bb762012-12-17 07:11:04830TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15831 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04832 PathService::Get(base::FILE_EXE, &app_path);
833 GURL app_url = FilePathToFileURL(app_path);
834
835 TestDelegate d;
836 {
davidben151423e2015-03-23 18:48:36837 scoped_ptr<URLRequest> r(
838 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04839
[email protected]f7022f32014-08-21 16:32:19840 r->Start();
841 EXPECT_TRUE(r->is_pending());
842 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04843 }
[email protected]79e1fd62013-06-20 06:50:04844 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04845 // destroyed.
[email protected]255620da2013-08-19 13:14:29846 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04847}
848
[email protected]316c1e5e2012-09-12 15:17:44849TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
850 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17851 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44852 FillBuffer(buffer.get(), buffer_size);
853
[email protected]6cdfd7f2013-02-08 20:40:15854 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52855 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44856 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30857 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44858
859 int64 file_size;
[email protected]56285702013-12-04 18:22:49860 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44861
862 const size_t first_byte_position = 500;
863 const size_t last_byte_position = buffer_size - first_byte_position;
864 const size_t content_length = last_byte_position - first_byte_position + 1;
865 std::string partial_buffer_string(buffer.get() + first_byte_position,
866 buffer.get() + last_byte_position + 1);
867
868 TestDelegate d;
869 {
davidben151423e2015-03-23 18:48:36870 scoped_ptr<URLRequest> r(
871 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44872
873 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38874 headers.SetHeader(
875 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59876 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38877 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19878 r->SetExtraRequestHeaders(headers);
879 r->Start();
880 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44881
[email protected]255620da2013-08-19 13:14:29882 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19883 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44884 EXPECT_EQ(1, d.response_started_count());
885 EXPECT_FALSE(d.received_data_before_response());
886 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
887 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
888 EXPECT_TRUE(partial_buffer_string == d.data_received());
889 }
890
[email protected]dd3aa792013-07-16 19:10:23891 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44892}
893
894TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
895 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17896 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44897 FillBuffer(buffer.get(), buffer_size);
898
[email protected]6cdfd7f2013-02-08 20:40:15899 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52900 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44901 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30902 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44903
904 int64 file_size;
[email protected]56285702013-12-04 18:22:49905 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44906
907 const size_t first_byte_position = 500;
908 const size_t last_byte_position = buffer_size - 1;
909 const size_t content_length = last_byte_position - first_byte_position + 1;
910 std::string partial_buffer_string(buffer.get() + first_byte_position,
911 buffer.get() + last_byte_position + 1);
912
913 TestDelegate d;
914 {
davidben151423e2015-03-23 18:48:36915 scoped_ptr<URLRequest> r(
916 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44917
918 HttpRequestHeaders headers;
919 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59920 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38921 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19922 r->SetExtraRequestHeaders(headers);
923 r->Start();
924 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44925
[email protected]255620da2013-08-19 13:14:29926 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19927 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44928 EXPECT_EQ(1, d.response_started_count());
929 EXPECT_FALSE(d.received_data_before_response());
930 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
931 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
932 EXPECT_TRUE(partial_buffer_string == d.data_received());
933 }
934
[email protected]dd3aa792013-07-16 19:10:23935 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44936}
937
938TEST_F(URLRequestTest, FileTestMultipleRanges) {
939 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17940 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44941 FillBuffer(buffer.get(), buffer_size);
942
[email protected]6cdfd7f2013-02-08 20:40:15943 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52944 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44945 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30946 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44947
948 int64 file_size;
[email protected]56285702013-12-04 18:22:49949 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44950
951 TestDelegate d;
952 {
davidben151423e2015-03-23 18:48:36953 scoped_ptr<URLRequest> r(
954 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44955
956 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38957 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19958 r->SetExtraRequestHeaders(headers);
959 r->Start();
960 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44961
[email protected]255620da2013-08-19 13:14:29962 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44963 EXPECT_TRUE(d.request_failed());
964 }
965
[email protected]dd3aa792013-07-16 19:10:23966 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44967}
968
[email protected]3ca8b362013-11-11 22:18:07969TEST_F(URLRequestTest, AllowFileURLs) {
970 base::ScopedTempDir temp_dir;
971 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
972 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52973 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07974 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:30975 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:59976 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:07977
978 {
979 TestDelegate d;
980 TestNetworkDelegate network_delegate;
981 network_delegate.set_can_access_files(true);
982 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36983 scoped_ptr<URLRequest> r(
984 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19985 r->Start();
[email protected]3ca8b362013-11-11 22:18:07986 base::RunLoop().Run();
987 EXPECT_FALSE(d.request_failed());
988 EXPECT_EQ(test_data, d.data_received());
989 }
990
991 {
992 TestDelegate d;
993 TestNetworkDelegate network_delegate;
994 network_delegate.set_can_access_files(false);
995 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36996 scoped_ptr<URLRequest> r(
997 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19998 r->Start();
[email protected]3ca8b362013-11-11 22:18:07999 base::RunLoop().Run();
1000 EXPECT_TRUE(d.request_failed());
1001 EXPECT_EQ("", d.data_received());
1002 }
1003}
1004
[email protected]316c1e5e2012-09-12 15:17:441005
1006TEST_F(URLRequestTest, FileDirCancelTest) {
1007 // Put in mock resource provider.
1008 NetModule::SetResourceProvider(TestNetResourceProvider);
1009
1010 TestDelegate d;
1011 {
[email protected]6cdfd7f2013-02-08 20:40:151012 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441013 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1014 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1015 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1016
[email protected]f7022f32014-08-21 16:32:191017 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361018 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191019 req->Start();
1020 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441021
1022 d.set_cancel_in_received_data_pending(true);
1023
[email protected]255620da2013-08-19 13:14:291024 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441025 }
1026
1027 // Take out mock resource provider.
1028 NetModule::SetResourceProvider(NULL);
1029}
1030
[email protected]5f9581402013-10-30 13:08:321031TEST_F(URLRequestTest, FileDirOutputSanity) {
1032 // Verify the general sanity of the the output of the file:
1033 // directory lister by checking for the output of a known existing
1034 // file.
1035 const char sentinel_name[] = "filedir-sentinel";
1036
1037 base::FilePath path;
1038 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471039 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321040
1041 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191042 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361043 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191044 req->Start();
[email protected]5f9581402013-10-30 13:08:321045 base::RunLoop().Run();
1046
1047 // Generate entry for the sentinel file.
1048 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581049 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491050 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321051 EXPECT_GT(info.size, 0);
1052 std::string sentinel_output = GetDirectoryListingEntry(
1053 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1054 std::string(sentinel_name),
1055 false /* is_dir */,
1056 info.size,
1057 info.last_modified);
1058
1059 ASSERT_LT(0, d.bytes_received());
1060 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191061 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:321062 // Check for the entry generated for the "sentinel" file.
1063 const std::string& data = d.data_received();
1064 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1065}
1066
[email protected]316c1e5e2012-09-12 15:17:441067TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1068 // There is an implicit redirect when loading a file path that matches a
1069 // directory and does not end with a slash. Ensure that following such
1070 // redirects does not crash. See http://crbug.com/18686.
1071
[email protected]6cdfd7f2013-02-08 20:40:151072 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441073 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471074 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441075
1076 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191077 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361078 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191079 req->Start();
[email protected]255620da2013-08-19 13:14:291080 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441081
1082 ASSERT_EQ(1, d.received_redirect_count());
1083 ASSERT_LT(0, d.bytes_received());
1084 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191085 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441086}
1087
1088#if defined(OS_WIN)
1089// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1090TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1091 TestDelegate d;
davidben151423e2015-03-23 18:48:361092 scoped_ptr<URLRequest> req(
1093 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191094 req->Start();
[email protected]255620da2013-08-19 13:14:291095 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441096
1097 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191098 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441099}
[email protected]5ecf7cb282014-05-11 01:49:551100#endif // defined(OS_WIN)
1101
1102#endif // !defined(DISABLE_FILE_SUPPORT)
1103
1104TEST_F(URLRequestTest, InvalidUrlTest) {
1105 TestDelegate d;
1106 {
[email protected]f7022f32014-08-21 16:32:191107 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361108 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551109
[email protected]f7022f32014-08-21 16:32:191110 r->Start();
1111 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551112
1113 base::RunLoop().Run();
1114 EXPECT_TRUE(d.request_failed());
1115 }
1116}
1117
jochen0e3b3a62014-09-16 18:31:231118TEST_F(URLRequestTest, InvalidReferrerTest) {
1119 TestURLRequestContext context;
1120 TestNetworkDelegate network_delegate;
1121 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1122 context.set_network_delegate(&network_delegate);
1123 TestDelegate d;
davidben151423e2015-03-23 18:48:361124 scoped_ptr<URLRequest> req(
1125 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231126 req->SetReferrer("https://somewhere.com/");
1127
1128 req->Start();
1129 base::RunLoop().Run();
1130 EXPECT_TRUE(d.request_failed());
1131}
1132
[email protected]5ecf7cb282014-05-11 01:49:551133#if defined(OS_WIN)
1134TEST_F(URLRequestTest, ResolveShortcutTest) {
1135 base::FilePath app_path;
1136 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471137 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551138 app_path = app_path.AppendASCII("with-headers.html");
1139
1140 std::wstring lnk_path = app_path.value() + L".lnk";
1141
1142 base::win::ScopedCOMInitializer com_initializer;
1143
1144 // Temporarily create a shortcut for test
1145 {
1146 base::win::ScopedComPtr<IShellLink> shell;
1147 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1148 CLSCTX_INPROC_SERVER)));
1149 base::win::ScopedComPtr<IPersistFile> persist;
1150 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1151 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1152 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1153 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1154 }
1155
1156 TestDelegate d;
1157 {
[email protected]f7022f32014-08-21 16:32:191158 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361159 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551160
[email protected]f7022f32014-08-21 16:32:191161 r->Start();
1162 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551163
1164 base::RunLoop().Run();
1165
1166 WIN32_FILE_ATTRIBUTE_DATA data;
1167 GetFileAttributesEx(app_path.value().c_str(),
1168 GetFileExInfoStandard, &data);
1169 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1170 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1171 FILE_ATTRIBUTE_NORMAL, NULL);
1172 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1173 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1174 DWORD read_size;
1175 BOOL result;
1176 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1177 &read_size, NULL);
1178 std::string content(buffer.get(), read_size);
1179 CloseHandle(file);
1180
[email protected]f7022f32014-08-21 16:32:191181 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551182 EXPECT_EQ(1, d.received_redirect_count());
1183 EXPECT_EQ(content, d.data_received());
1184 }
1185
1186 // Clean the shortcut
1187 DeleteFile(lnk_path.c_str());
1188}
1189#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441190
1191// Custom URLRequestJobs for use with interceptor tests
1192class RestartTestJob : public URLRequestTestJob {
1193 public:
1194 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1195 : URLRequestTestJob(request, network_delegate, true) {}
1196 protected:
dchengb03027d2014-10-21 12:00:201197 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441198 private:
dchengb03027d2014-10-21 12:00:201199 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441200};
1201
1202class CancelTestJob : public URLRequestTestJob {
1203 public:
1204 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1205 : URLRequestTestJob(request, network_delegate, true) {}
1206 protected:
dchengb03027d2014-10-21 12:00:201207 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441208 private:
dchengb03027d2014-10-21 12:00:201209 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441210};
1211
1212class CancelThenRestartTestJob : public URLRequestTestJob {
1213 public:
1214 explicit CancelThenRestartTestJob(URLRequest* request,
1215 NetworkDelegate* network_delegate)
1216 : URLRequestTestJob(request, network_delegate, true) {
1217 }
1218 protected:
dchengb03027d2014-10-21 12:00:201219 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441220 request_->Cancel();
1221 this->NotifyRestartRequired();
1222 }
1223 private:
dchengb03027d2014-10-21 12:00:201224 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441225};
1226
bengr1bf8e942014-11-07 01:36:501227// An Interceptor for use with interceptor tests.
1228class MockURLRequestInterceptor : public URLRequestInterceptor {
1229 public:
1230 // Static getters for canned response header and data strings.
1231 static std::string ok_data() {
1232 return URLRequestTestJob::test_data_1();
1233 }
1234
1235 static std::string ok_headers() {
1236 return URLRequestTestJob::test_headers();
1237 }
1238
1239 static std::string redirect_data() {
1240 return std::string();
1241 }
1242
1243 static std::string redirect_headers() {
1244 return URLRequestTestJob::test_redirect_headers();
1245 }
1246
1247 static std::string error_data() {
1248 return std::string("ohhh nooooo mr. bill!");
1249 }
1250
1251 static std::string error_headers() {
1252 return URLRequestTestJob::test_error_headers();
1253 }
1254
1255 MockURLRequestInterceptor()
1256 : intercept_main_request_(false), restart_main_request_(false),
1257 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1258 simulate_main_network_error_(false),
1259 intercept_redirect_(false), cancel_redirect_request_(false),
1260 intercept_final_response_(false), cancel_final_request_(false),
1261 use_url_request_http_job_(false),
1262 did_intercept_main_(false), did_restart_main_(false),
1263 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1264 did_simulate_error_main_(false),
1265 did_intercept_redirect_(false), did_cancel_redirect_(false),
1266 did_intercept_final_(false), did_cancel_final_(false) {
1267 }
1268
1269 ~MockURLRequestInterceptor() override {
1270 }
1271
1272 // URLRequestInterceptor implementation:
1273 URLRequestJob* MaybeInterceptRequest(
1274 URLRequest* request,
1275 NetworkDelegate* network_delegate) const override {
1276 if (restart_main_request_) {
1277 restart_main_request_ = false;
1278 did_restart_main_ = true;
1279 return new RestartTestJob(request, network_delegate);
1280 }
1281 if (cancel_main_request_) {
1282 cancel_main_request_ = false;
1283 did_cancel_main_ = true;
1284 return new CancelTestJob(request, network_delegate);
1285 }
1286 if (cancel_then_restart_main_request_) {
1287 cancel_then_restart_main_request_ = false;
1288 did_cancel_then_restart_main_ = true;
1289 return new CancelThenRestartTestJob(request, network_delegate);
1290 }
1291 if (simulate_main_network_error_) {
1292 simulate_main_network_error_ = false;
1293 did_simulate_error_main_ = true;
1294 if (use_url_request_http_job_) {
1295 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1296 }
1297 // This job will result in error since the requested URL is not one of the
1298 // URLs supported by these tests.
1299 return new URLRequestTestJob(request, network_delegate, true);
1300 }
1301 if (!intercept_main_request_)
1302 return nullptr;
1303 intercept_main_request_ = false;
1304 did_intercept_main_ = true;
1305 URLRequestTestJob* job = new URLRequestTestJob(request,
1306 network_delegate,
1307 main_headers_,
1308 main_data_,
1309 true);
1310 job->set_load_timing_info(main_request_load_timing_info_);
1311 return job;
1312 }
1313
1314 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1315 NetworkDelegate* network_delegate,
1316 const GURL& location) const override {
1317 if (cancel_redirect_request_) {
1318 cancel_redirect_request_ = false;
1319 did_cancel_redirect_ = true;
1320 return new CancelTestJob(request, network_delegate);
1321 }
1322 if (!intercept_redirect_)
1323 return nullptr;
1324 intercept_redirect_ = false;
1325 did_intercept_redirect_ = true;
1326 if (use_url_request_http_job_) {
1327 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1328 }
1329 return new URLRequestTestJob(request,
1330 network_delegate,
1331 redirect_headers_,
1332 redirect_data_,
1333 true);
1334 }
1335
1336 URLRequestJob* MaybeInterceptResponse(
1337 URLRequest* request,
1338 NetworkDelegate* network_delegate) const override {
1339 if (cancel_final_request_) {
1340 cancel_final_request_ = false;
1341 did_cancel_final_ = true;
1342 return new CancelTestJob(request, network_delegate);
1343 }
1344 if (!intercept_final_response_)
1345 return nullptr;
1346 intercept_final_response_ = false;
1347 did_intercept_final_ = true;
1348 if (use_url_request_http_job_) {
1349 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1350 }
1351 return new URLRequestTestJob(request,
1352 network_delegate,
1353 final_headers_,
1354 final_data_,
1355 true);
1356 }
1357
1358 void set_intercept_main_request(bool intercept_main_request) {
1359 intercept_main_request_ = intercept_main_request;
1360 }
1361
1362 void set_main_headers(const std::string& main_headers) {
1363 main_headers_ = main_headers;
1364 }
1365
1366 void set_main_data(const std::string& main_data) {
1367 main_data_ = main_data;
1368 }
1369
1370 void set_main_request_load_timing_info(
1371 const LoadTimingInfo& main_request_load_timing_info) {
1372 main_request_load_timing_info_ = main_request_load_timing_info;
1373 }
1374
1375 void set_restart_main_request(bool restart_main_request) {
1376 restart_main_request_ = restart_main_request;
1377 }
1378
1379 void set_cancel_main_request(bool cancel_main_request) {
1380 cancel_main_request_ = cancel_main_request;
1381 }
1382
1383 void set_cancel_then_restart_main_request(
1384 bool cancel_then_restart_main_request) {
1385 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1386 }
1387
1388 void set_simulate_main_network_error(bool simulate_main_network_error) {
1389 simulate_main_network_error_ = simulate_main_network_error;
1390 }
1391
1392 void set_intercept_redirect(bool intercept_redirect) {
1393 intercept_redirect_ = intercept_redirect;
1394 }
1395
1396 void set_redirect_headers(const std::string& redirect_headers) {
1397 redirect_headers_ = redirect_headers;
1398 }
1399
1400 void set_redirect_data(const std::string& redirect_data) {
1401 redirect_data_ = redirect_data;
1402 }
1403
1404 void set_cancel_redirect_request(bool cancel_redirect_request) {
1405 cancel_redirect_request_ = cancel_redirect_request;
1406 }
1407
1408 void set_intercept_final_response(bool intercept_final_response) {
1409 intercept_final_response_ = intercept_final_response;
1410 }
1411
1412 void set_final_headers(const std::string& final_headers) {
1413 final_headers_ = final_headers;
1414 }
1415
1416 void set_final_data(const std::string& final_data) {
1417 final_data_ = final_data;
1418 }
1419
1420 void set_cancel_final_request(bool cancel_final_request) {
1421 cancel_final_request_ = cancel_final_request;
1422 }
1423
1424 void set_use_url_request_http_job(bool use_url_request_http_job) {
1425 use_url_request_http_job_ = use_url_request_http_job;
1426 }
1427
1428 bool did_intercept_main() const {
1429 return did_intercept_main_;
1430 }
1431
1432 bool did_restart_main() const {
1433 return did_restart_main_;
1434 }
1435
1436 bool did_cancel_main() const {
1437 return did_cancel_main_;
1438 }
1439
1440 bool did_cancel_then_restart_main() const {
1441 return did_cancel_then_restart_main_;
1442 }
1443
1444 bool did_simulate_error_main() const {
1445 return did_simulate_error_main_;
1446 }
1447
1448 bool did_intercept_redirect() const {
1449 return did_intercept_redirect_;
1450 }
1451
1452 bool did_cancel_redirect() const {
1453 return did_cancel_redirect_;
1454 }
1455
1456 bool did_intercept_final() const {
1457 return did_intercept_final_;
1458 }
1459
1460 bool did_cancel_final() const {
1461 return did_cancel_final_;
1462 }
1463
1464 private:
1465 // Indicate whether to intercept the main request, and if so specify the
1466 // response to return and the LoadTimingInfo to use.
1467 mutable bool intercept_main_request_;
1468 mutable std::string main_headers_;
1469 mutable std::string main_data_;
1470 mutable LoadTimingInfo main_request_load_timing_info_;
1471
1472 // These indicate actions that can be taken within MaybeInterceptRequest.
1473 mutable bool restart_main_request_;
1474 mutable bool cancel_main_request_;
1475 mutable bool cancel_then_restart_main_request_;
1476 mutable bool simulate_main_network_error_;
1477
1478 // Indicate whether to intercept redirects, and if so specify the response to
1479 // return.
1480 mutable bool intercept_redirect_;
1481 mutable std::string redirect_headers_;
1482 mutable std::string redirect_data_;
1483
1484 // Cancel the request within MaybeInterceptRedirect.
1485 mutable bool cancel_redirect_request_;
1486
1487 // Indicate whether to intercept the final response, and if so specify the
1488 // response to return.
1489 mutable bool intercept_final_response_;
1490 mutable std::string final_headers_;
1491 mutable std::string final_data_;
1492
1493 // Cancel the final request within MaybeInterceptResponse.
1494 mutable bool cancel_final_request_;
1495
1496 // Instruct the interceptor to use a real URLRequestHTTPJob.
1497 mutable bool use_url_request_http_job_;
1498
1499 // These indicate if the interceptor did something or not.
1500 mutable bool did_intercept_main_;
1501 mutable bool did_restart_main_;
1502 mutable bool did_cancel_main_;
1503 mutable bool did_cancel_then_restart_main_;
1504 mutable bool did_simulate_error_main_;
1505 mutable bool did_intercept_redirect_;
1506 mutable bool did_cancel_redirect_;
1507 mutable bool did_intercept_final_;
1508 mutable bool did_cancel_final_;
1509};
1510
1511// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1512class URLRequestInterceptorTest : public URLRequestTest {
1513 public:
1514 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1515 }
1516
1517 ~URLRequestInterceptorTest() override {
1518 // URLRequestJobs may post clean-up tasks on destruction.
1519 base::RunLoop().RunUntilIdle();
1520 }
1521
1522 void SetUpFactory() override {
1523 interceptor_ = new MockURLRequestInterceptor();
1524 job_factory_.reset(new URLRequestInterceptingJobFactory(
1525 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1526 }
1527
1528 MockURLRequestInterceptor* interceptor() const {
1529 return interceptor_;
1530 }
1531
1532 private:
1533 MockURLRequestInterceptor* interceptor_;
1534};
1535
1536TEST_F(URLRequestInterceptorTest, Intercept) {
1537 // Intercept the main request and respond with a simple response.
1538 interceptor()->set_intercept_main_request(true);
1539 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1540 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591541 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501542 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361543 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501544 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1545 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1546 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1547 req->SetUserData(nullptr, user_data0);
1548 req->SetUserData(&user_data1, user_data1);
1549 req->SetUserData(&user_data2, user_data2);
1550 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191551 req->Start();
[email protected]255620da2013-08-19 13:14:291552 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591553
bengr1bf8e942014-11-07 01:36:501554 // Make sure we can retrieve our specific user data.
1555 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1556 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1557 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591558
bengr1bf8e942014-11-07 01:36:501559 // Check that we got one good response.
1560 EXPECT_TRUE(req->status().is_success());
1561 EXPECT_EQ(200, req->response_headers()->response_code());
1562 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1563 EXPECT_EQ(1, d.response_started_count());
1564 EXPECT_EQ(0, d.received_redirect_count());
1565}
[email protected]2bba3252013-04-08 19:50:591566
bengr1bf8e942014-11-07 01:36:501567TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1568 // Intercept the main request and respond with a redirect.
1569 interceptor()->set_intercept_main_request(true);
1570 interceptor()->set_main_headers(
1571 MockURLRequestInterceptor::redirect_headers());
1572 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1573
1574 // Intercept that redirect and respond with a final OK response.
1575 interceptor()->set_intercept_redirect(true);
1576 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1577 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1578
1579 TestDelegate d;
1580 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361581 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501582 req->set_method("GET");
1583 req->Start();
1584 base::RunLoop().Run();
1585
1586 // Check that the interceptor got called as expected.
1587 EXPECT_TRUE(interceptor()->did_intercept_main());
1588 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1589
1590 // Check that we got one good response.
1591 EXPECT_TRUE(req->status().is_success());
1592 if (req->status().is_success())
1593 EXPECT_EQ(200, req->response_headers()->response_code());
1594
1595 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1596 EXPECT_EQ(1, d.response_started_count());
1597 EXPECT_EQ(0, d.received_redirect_count());
1598}
1599
1600TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1601 // Intercept the main request to generate a server error response.
1602 interceptor()->set_intercept_main_request(true);
1603 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1604 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1605
1606 // Intercept that error and respond with an OK response.
1607 interceptor()->set_intercept_final_response(true);
1608 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1609 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1610
1611 TestDelegate d;
1612 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361613 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501614 req->set_method("GET");
1615 req->Start();
1616 base::RunLoop().Run();
1617
1618 // Check that the interceptor got called as expected.
1619 EXPECT_TRUE(interceptor()->did_intercept_main());
1620 EXPECT_TRUE(interceptor()->did_intercept_final());
1621
1622 // Check that we got one good response.
1623 EXPECT_TRUE(req->status().is_success());
1624 EXPECT_EQ(200, req->response_headers()->response_code());
1625 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1626 EXPECT_EQ(1, d.response_started_count());
1627 EXPECT_EQ(0, d.received_redirect_count());
1628}
1629
1630TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1631 // Intercept the main request to simulate a network error.
1632 interceptor()->set_simulate_main_network_error(true);
1633
1634 // Intercept that error and respond with an OK response.
1635 interceptor()->set_intercept_final_response(true);
1636 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1637 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1638
1639 TestDelegate d;
1640 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361641 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501642 req->set_method("GET");
1643 req->Start();
1644 base::RunLoop().Run();
1645
1646 // Check that the interceptor got called as expected.
1647 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1648 EXPECT_TRUE(interceptor()->did_intercept_final());
1649
1650 // Check that we received one good response.
1651 EXPECT_TRUE(req->status().is_success());
1652 EXPECT_EQ(200, req->response_headers()->response_code());
1653 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1654 EXPECT_EQ(1, d.response_started_count());
1655 EXPECT_EQ(0, d.received_redirect_count());
1656}
1657
1658TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1659 // Restart the main request.
1660 interceptor()->set_restart_main_request(true);
1661
1662 // then intercept the new main request and respond with an OK response
1663 interceptor()->set_intercept_main_request(true);
1664 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1665 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1666
1667 TestDelegate d;
1668 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361669 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501670 req->set_method("GET");
1671 req->Start();
1672 base::RunLoop().Run();
1673
1674 // Check that the interceptor got called as expected.
1675 EXPECT_TRUE(interceptor()->did_restart_main());
1676 EXPECT_TRUE(interceptor()->did_intercept_main());
1677
1678 // Check that we received one good response.
1679 EXPECT_TRUE(req->status().is_success());
1680 if (req->status().is_success())
1681 EXPECT_EQ(200, req->response_headers()->response_code());
1682
1683 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1684 EXPECT_EQ(1, d.response_started_count());
1685 EXPECT_EQ(0, d.received_redirect_count());
1686}
1687
1688TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1689 // Intercept the main request and cancel from within the restarted job.
1690 interceptor()->set_cancel_main_request(true);
1691
1692 // Set up to intercept the final response and override it with an OK response.
1693 interceptor()->set_intercept_final_response(true);
1694 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1695 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1696
1697 TestDelegate d;
1698 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361699 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501700 req->set_method("GET");
1701 req->Start();
1702 base::RunLoop().Run();
1703
1704 // Check that the interceptor got called as expected.
1705 EXPECT_TRUE(interceptor()->did_cancel_main());
1706 EXPECT_FALSE(interceptor()->did_intercept_final());
1707
1708 // Check that we see a canceled request.
1709 EXPECT_FALSE(req->status().is_success());
1710 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1711}
1712
1713TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1714 // Intercept the main request and respond with a redirect.
1715 interceptor()->set_intercept_main_request(true);
1716 interceptor()->set_main_headers(
1717 MockURLRequestInterceptor::redirect_headers());
1718 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1719
1720 // Intercept the redirect and cancel from within that job.
1721 interceptor()->set_cancel_redirect_request(true);
1722
1723 // Set up to intercept the final response and override it with an OK response.
1724 interceptor()->set_intercept_final_response(true);
1725 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1726 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1727
1728 TestDelegate d;
1729 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361730 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501731 req->set_method("GET");
1732 req->Start();
1733 base::RunLoop().Run();
1734
1735 // Check that the interceptor got called as expected.
1736 EXPECT_TRUE(interceptor()->did_intercept_main());
1737 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1738 EXPECT_FALSE(interceptor()->did_intercept_final());
1739
1740 // Check that we see a canceled request.
1741 EXPECT_FALSE(req->status().is_success());
1742 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1743}
1744
1745TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1746 // Intercept the main request to simulate a network error.
1747 interceptor()->set_simulate_main_network_error(true);
1748
1749 // Set up to intercept final the response and cancel from within that job.
1750 interceptor()->set_cancel_final_request(true);
1751
1752 TestDelegate d;
1753 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361754 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501755 req->set_method("GET");
1756 req->Start();
1757 base::RunLoop().Run();
1758
1759 // Check that the interceptor got called as expected.
1760 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1761 EXPECT_TRUE(interceptor()->did_cancel_final());
1762
1763 // Check that we see a canceled request.
1764 EXPECT_FALSE(req->status().is_success());
1765 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1766}
1767
1768TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1769 // Intercept the main request and cancel then restart from within that job.
1770 interceptor()->set_cancel_then_restart_main_request(true);
1771
1772 // Set up to intercept the final response and override it with an OK response.
1773 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501774 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1775 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501776
1777 TestDelegate d;
1778 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361779 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501780 req->set_method("GET");
1781 req->Start();
1782 base::RunLoop().Run();
1783
1784 // Check that the interceptor got called as expected.
1785 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1786 EXPECT_FALSE(interceptor()->did_intercept_final());
1787
1788 // Check that we see a canceled request.
1789 EXPECT_FALSE(req->status().is_success());
1790 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591791}
1792
1793// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1794// reused. |connect_time_flags| is used to indicate if there should be dns
1795// or SSL times, and |used_proxy| is used for proxy times.
1796LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1797 int connect_time_flags,
1798 bool used_proxy) {
1799 LoadTimingInfo load_timing;
1800 load_timing.socket_log_id = 1;
1801
1802 if (used_proxy) {
1803 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1804 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1805 }
1806
1807 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1808 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1809 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1810 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1811 }
1812 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1813 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1814 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1815 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1816 }
1817 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1818
1819 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1820 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1821 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1822 return load_timing;
1823}
1824
1825// Same as above, but in the case of a reused socket.
1826LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1827 bool used_proxy) {
1828 LoadTimingInfo load_timing;
1829 load_timing.socket_log_id = 1;
1830 load_timing.socket_reused = true;
1831
1832 if (used_proxy) {
1833 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1834 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1835 }
1836
1837 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1838 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1839 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1840 return load_timing;
1841}
1842
bengr1bf8e942014-11-07 01:36:501843LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1844 const LoadTimingInfo& job_load_timing,
1845 const URLRequestContext& context,
1846 MockURLRequestInterceptor* interceptor) {
1847 interceptor->set_intercept_main_request(true);
1848 interceptor->set_main_request_load_timing_info(job_load_timing);
1849 TestDelegate d;
1850 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361851 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501852 req->Start();
1853 base::RunLoop().Run();
1854
1855 LoadTimingInfo resulting_load_timing;
1856 req->GetLoadTimingInfo(&resulting_load_timing);
1857
1858 // None of these should be modified by the URLRequest.
1859 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1860 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1861 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1862 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1863 EXPECT_EQ(job_load_timing.receive_headers_end,
1864 resulting_load_timing.receive_headers_end);
1865
1866 return resulting_load_timing;
1867}
1868
[email protected]2bba3252013-04-08 19:50:591869// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501870TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591871 base::TimeTicks now = base::TimeTicks::Now();
1872 LoadTimingInfo job_load_timing =
1873 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1874
[email protected]2ca01e52013-10-31 22:05:191875 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501876 RunURLRequestInterceptorLoadTimingTest(
1877 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591878
1879 // Nothing should have been changed by the URLRequest.
1880 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1881 load_timing_result.proxy_resolve_start);
1882 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1883 load_timing_result.proxy_resolve_end);
1884 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1885 load_timing_result.connect_timing.dns_start);
1886 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1887 load_timing_result.connect_timing.dns_end);
1888 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1889 load_timing_result.connect_timing.connect_start);
1890 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1891 load_timing_result.connect_timing.connect_end);
1892 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1893 load_timing_result.connect_timing.ssl_start);
1894 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1895 load_timing_result.connect_timing.ssl_end);
1896
1897 // Redundant sanity check.
1898 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1899}
1900
1901// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501902TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591903 base::TimeTicks now = base::TimeTicks::Now();
1904 LoadTimingInfo job_load_timing =
1905 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1906
[email protected]2ca01e52013-10-31 22:05:191907 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501908 RunURLRequestInterceptorLoadTimingTest(
1909 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591910
1911 // Nothing should have been changed by the URLRequest.
1912 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1913 load_timing_result.proxy_resolve_start);
1914 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1915 load_timing_result.proxy_resolve_end);
1916 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1917 load_timing_result.connect_timing.dns_start);
1918 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1919 load_timing_result.connect_timing.dns_end);
1920 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1921 load_timing_result.connect_timing.connect_start);
1922 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1923 load_timing_result.connect_timing.connect_end);
1924 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1925 load_timing_result.connect_timing.ssl_start);
1926 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1927 load_timing_result.connect_timing.ssl_end);
1928
1929 // Redundant sanity check.
1930 TestLoadTimingNotReusedWithProxy(load_timing_result,
1931 CONNECT_TIMING_HAS_SSL_TIMES);
1932}
1933
1934// Make sure that URLRequest correctly adjusts proxy times when they're before
1935// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101936// the case of reusing a SPDY session. The connected socket is not considered
1937// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591938//
1939// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501940TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591941 base::TimeTicks now = base::TimeTicks::Now();
1942 LoadTimingInfo job_load_timing =
1943 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1944 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1945 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1946 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1947 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1948 job_load_timing.connect_timing.connect_start =
1949 now - base::TimeDelta::FromDays(2);
1950 job_load_timing.connect_timing.connect_end =
1951 now - base::TimeDelta::FromDays(1);
1952
[email protected]2ca01e52013-10-31 22:05:191953 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501954 RunURLRequestInterceptorLoadTimingTest(
1955 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591956
1957 // Proxy times, connect times, and DNS times should all be replaced with
1958 // request_start.
1959 EXPECT_EQ(load_timing_result.request_start,
1960 load_timing_result.proxy_resolve_start);
1961 EXPECT_EQ(load_timing_result.request_start,
1962 load_timing_result.proxy_resolve_end);
1963 EXPECT_EQ(load_timing_result.request_start,
1964 load_timing_result.connect_timing.dns_start);
1965 EXPECT_EQ(load_timing_result.request_start,
1966 load_timing_result.connect_timing.dns_end);
1967 EXPECT_EQ(load_timing_result.request_start,
1968 load_timing_result.connect_timing.connect_start);
1969 EXPECT_EQ(load_timing_result.request_start,
1970 load_timing_result.connect_timing.connect_end);
1971
1972 // Other times should have been left null.
1973 TestLoadTimingNotReusedWithProxy(load_timing_result,
1974 CONNECT_TIMING_HAS_DNS_TIMES);
1975}
1976
1977// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:501978TEST_F(URLRequestInterceptorTest,
1979 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:591980 base::TimeTicks now = base::TimeTicks::Now();
1981 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1982 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1983 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1984
[email protected]2ca01e52013-10-31 22:05:191985 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501986 RunURLRequestInterceptorLoadTimingTest(
1987 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591988
1989 // Proxy times and connect times should all be replaced with request_start.
1990 EXPECT_EQ(load_timing_result.request_start,
1991 load_timing_result.proxy_resolve_start);
1992 EXPECT_EQ(load_timing_result.request_start,
1993 load_timing_result.proxy_resolve_end);
1994
1995 // Other times should have been left null.
1996 TestLoadTimingReusedWithProxy(load_timing_result);
1997}
1998
1999// Make sure that URLRequest correctly adjusts connect times when they're before
2000// |request_start|, due to reusing a connected socket. The connected socket is
2001// not considered reused in this test (May be a preconnect).
2002//
2003// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502004TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592005 base::TimeTicks now = base::TimeTicks::Now();
2006 LoadTimingInfo job_load_timing =
2007 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2008 job_load_timing.connect_timing.connect_start =
2009 now - base::TimeDelta::FromDays(1);
2010 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2011 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2012 job_load_timing.connect_timing.connect_end =
2013 now - base::TimeDelta::FromDays(4);
2014
[email protected]2ca01e52013-10-31 22:05:192015 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502016 RunURLRequestInterceptorLoadTimingTest(
2017 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592018
2019 // Connect times, and SSL times should be replaced with request_start.
2020 EXPECT_EQ(load_timing_result.request_start,
2021 load_timing_result.connect_timing.connect_start);
2022 EXPECT_EQ(load_timing_result.request_start,
2023 load_timing_result.connect_timing.ssl_start);
2024 EXPECT_EQ(load_timing_result.request_start,
2025 load_timing_result.connect_timing.ssl_end);
2026 EXPECT_EQ(load_timing_result.request_start,
2027 load_timing_result.connect_timing.connect_end);
2028
2029 // Other times should have been left null.
2030 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2031}
2032
2033// Make sure that URLRequest correctly adjusts connect times when they're before
2034// |request_start|, due to reusing a connected socket in the case that there
2035// are also proxy times. The connected socket is not considered reused in this
2036// test (May be a preconnect).
2037//
2038// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502039TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592040 base::TimeTicks now = base::TimeTicks::Now();
2041 LoadTimingInfo job_load_timing =
2042 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2043 job_load_timing.connect_timing.connect_start =
2044 now - base::TimeDelta::FromDays(1);
2045 job_load_timing.connect_timing.connect_end =
2046 now - base::TimeDelta::FromDays(2);
2047
[email protected]2ca01e52013-10-31 22:05:192048 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502049 RunURLRequestInterceptorLoadTimingTest(
2050 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592051
2052 // Connect times should be replaced with proxy_resolve_end.
2053 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2054 load_timing_result.connect_timing.connect_start);
2055 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2056 load_timing_result.connect_timing.connect_end);
2057
2058 // Other times should have been left null.
2059 TestLoadTimingNotReusedWithProxy(load_timing_result,
2060 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2061}
2062
[email protected]316c1e5e2012-09-12 15:17:442063// Check that two different URL requests have different identifiers.
2064TEST_F(URLRequestTest, Identifiers) {
2065 TestDelegate d;
2066 TestURLRequestContext context;
davidben151423e2015-03-23 18:48:362067 scoped_ptr<URLRequest> req(
2068 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2069 scoped_ptr<URLRequest> other_req(
2070 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442071
mmenke19378d22014-09-09 04:12:592072 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442073}
2074
2075// Check that a failure to connect to the proxy is reported to the network
2076// delegate.
2077TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2078 MockHostResolver host_resolver;
2079 host_resolver.rules()->AddSimulatedFailure("*");
2080
[email protected]ceefd7fd2012-11-29 00:36:242081 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442082 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2083
2084 TestDelegate d;
davidben151423e2015-03-23 18:48:362085 scoped_ptr<URLRequest> req(
2086 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192087 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442088
[email protected]f7022f32014-08-21 16:32:192089 req->Start();
[email protected]255620da2013-08-19 13:14:292090 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442091
2092 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192093 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152094 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192095 EXPECT_TRUE(req->proxy_server().IsEmpty());
2096 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2097 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442098
2099 EXPECT_EQ(1, network_delegate.error_count());
2100 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2101 EXPECT_EQ(1, network_delegate.completed_requests());
2102}
2103
[email protected]cba24642014-08-15 20:49:592104// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442105// content is empty.
2106TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2107 TestDelegate d;
davidben151423e2015-03-23 18:48:362108 scoped_ptr<URLRequest> req(
2109 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192110 req->Start();
[email protected]255620da2013-08-19 13:14:292111 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442112 EXPECT_EQ("", d.data_received());
2113 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2114}
2115
[email protected]5033ab82013-03-22 20:17:462116// Make sure that SetPriority actually sets the URLRequest's priority
2117// correctly, both before and after start.
2118TEST_F(URLRequestTest, SetPriorityBasic) {
2119 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192120 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362121 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192122 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462123
[email protected]f7022f32014-08-21 16:32:192124 req->SetPriority(LOW);
2125 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462126
[email protected]f7022f32014-08-21 16:32:192127 req->Start();
2128 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462129
[email protected]f7022f32014-08-21 16:32:192130 req->SetPriority(MEDIUM);
2131 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462132}
2133
2134// Make sure that URLRequest calls SetPriority on a job before calling
2135// Start on it.
2136TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2137 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192138 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362139 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192140 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462141
2142 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192143 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502144 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462145 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2146
[email protected]f7022f32014-08-21 16:32:192147 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462148
[email protected]f7022f32014-08-21 16:32:192149 req->Start();
[email protected]5033ab82013-03-22 20:17:462150 EXPECT_EQ(LOW, job->priority());
2151}
2152
2153// Make sure that URLRequest passes on its priority updates to its
2154// job.
2155TEST_F(URLRequestTest, SetJobPriority) {
2156 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192157 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362158 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462159
2160 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192161 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502162 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462163
[email protected]f7022f32014-08-21 16:32:192164 req->SetPriority(LOW);
2165 req->Start();
[email protected]5033ab82013-03-22 20:17:462166 EXPECT_EQ(LOW, job->priority());
2167
[email protected]f7022f32014-08-21 16:32:192168 req->SetPriority(MEDIUM);
2169 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462170 EXPECT_EQ(MEDIUM, job->priority());
2171}
2172
[email protected]bb1c4662013-11-14 00:00:072173// Setting the IGNORE_LIMITS load flag should be okay if the priority
2174// is MAXIMUM_PRIORITY.
2175TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2176 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192177 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362178 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192179 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072180
2181 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192182 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]bb1c4662013-11-14 00:00:072183 AddTestInterceptor()->set_main_intercept_job(job.get());
2184
[email protected]f7022f32014-08-21 16:32:192185 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2186 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072187
[email protected]f7022f32014-08-21 16:32:192188 req->SetPriority(MAXIMUM_PRIORITY);
2189 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072190
[email protected]f7022f32014-08-21 16:32:192191 req->Start();
2192 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072193 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2194}
2195
[email protected]ce7d0cbc2013-05-03 18:57:222196// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:442197#if !defined(OS_IOS)
nick5d570de92015-05-04 20:16:162198namespace {
2199
2200// Less verbose way of running a simple testserver for the tests below.
[email protected]ce7d0cbc2013-05-03 18:57:222201class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442202 public:
[email protected]6cdfd7f2013-02-08 20:40:152203 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:222204 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162205 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222206 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:442207 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:222208 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162209 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222210 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:442211};
2212
estarkcd39c11f2015-10-19 19:46:362213scoped_ptr<net::test_server::HttpResponse> HandleSetCookieRequest(
2214 const test_server::HttpRequest& request) {
2215 scoped_ptr<test_server::BasicHttpResponse> http_response(
2216 new test_server::BasicHttpResponse());
2217 if (request.relative_url.find("/set-cookie?") != 0) {
2218 http_response->set_code(net::HTTP_NOT_FOUND);
2219 http_response->set_content("hello");
2220 return http_response.Pass();
2221 }
2222 http_response->set_code(net::HTTP_OK);
2223 http_response->set_content("hello");
2224 http_response->set_content_type("text/plain");
2225 http_response->AddCustomHeader(
2226 "Set-Cookie",
2227 request.relative_url.substr(request.relative_url.find("?") + 1));
2228 return http_response.Pass();
2229}
2230
nick5d570de92015-05-04 20:16:162231} // namespace
2232
[email protected]f2f31b32013-01-16 23:24:092233TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442234 LocalHttpTestServer test_server;
2235 ASSERT_TRUE(test_server.Start());
2236
2237 TestURLRequestContext context;
2238 scoped_refptr<DelayedCookieMonster> delayed_cm =
2239 new DelayedCookieMonster();
2240 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502241 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442242
2243 // Set up a cookie.
2244 {
2245 TestNetworkDelegate network_delegate;
2246 context.set_network_delegate(&network_delegate);
2247 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192248 scoped_ptr<URLRequest> req(context.CreateRequest(
2249 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362250 &d));
[email protected]f7022f32014-08-21 16:32:192251 req->Start();
[email protected]255620da2013-08-19 13:14:292252 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442253 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2254 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2255 EXPECT_EQ(1, network_delegate.set_cookie_count());
2256 }
2257
2258 // Verify that the cookie is set.
2259 {
2260 TestNetworkDelegate network_delegate;
2261 context.set_network_delegate(&network_delegate);
2262 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192263 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:362264 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192265 req->Start();
[email protected]255620da2013-08-19 13:14:292266 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442267
2268 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2269 != std::string::npos);
2270 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2271 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2272 }
2273}
2274
[email protected]f2f31b32013-01-16 23:24:092275TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442276 LocalHttpTestServer test_server;
2277 ASSERT_TRUE(test_server.Start());
2278
2279 // Set up a 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(
2285 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362286 &d));
[email protected]f7022f32014-08-21 16:32:192287 req->Start();
[email protected]255620da2013-08-19 13:14:292288 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442289 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2290 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2291 }
2292
2293 // Verify that the cookie is set.
2294 {
2295 TestNetworkDelegate network_delegate;
2296 default_context_.set_network_delegate(&network_delegate);
2297 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192298 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362299 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192300 req->Start();
[email protected]255620da2013-08-19 13:14:292301 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442302
2303 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2304 != std::string::npos);
2305 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2306 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2307 }
2308
2309 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2310 {
2311 TestNetworkDelegate network_delegate;
2312 default_context_.set_network_delegate(&network_delegate);
2313 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192314 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362315 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192316 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2317 req->Start();
[email protected]255620da2013-08-19 13:14:292318 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442319
2320 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2321 == std::string::npos);
2322
2323 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2324 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2325 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2326 }
2327}
2328
2329TEST_F(URLRequestTest, DoNotSaveCookies) {
2330 LocalHttpTestServer test_server;
2331 ASSERT_TRUE(test_server.Start());
2332
2333 // Set up a cookie.
2334 {
2335 TestNetworkDelegate network_delegate;
2336 default_context_.set_network_delegate(&network_delegate);
2337 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192338 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2339 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362340 &d));
[email protected]f7022f32014-08-21 16:32:192341 req->Start();
[email protected]255620da2013-08-19 13:14:292342 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442343
2344 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2345 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2346 EXPECT_EQ(1, network_delegate.set_cookie_count());
2347 }
2348
2349 // Try to set-up another cookie and update the previous cookie.
2350 {
2351 TestNetworkDelegate network_delegate;
2352 default_context_.set_network_delegate(&network_delegate);
2353 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192354 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442355 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362356 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192357 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2358 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442359
[email protected]255620da2013-08-19 13:14:292360 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442361
2362 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2363 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2364 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2365 EXPECT_EQ(0, network_delegate.set_cookie_count());
2366 }
2367
2368 // Verify the cookies weren't saved or updated.
2369 {
2370 TestNetworkDelegate network_delegate;
2371 default_context_.set_network_delegate(&network_delegate);
2372 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192373 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362374 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192375 req->Start();
[email protected]255620da2013-08-19 13:14:292376 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442377
2378 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2379 == std::string::npos);
2380 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2381 != std::string::npos);
2382
2383 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2384 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2385 EXPECT_EQ(0, network_delegate.set_cookie_count());
2386 }
2387}
2388
2389TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2390 LocalHttpTestServer test_server;
2391 ASSERT_TRUE(test_server.Start());
2392
2393 // Set up a cookie.
2394 {
2395 TestNetworkDelegate network_delegate;
2396 default_context_.set_network_delegate(&network_delegate);
2397 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192398 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2399 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362400 &d));
[email protected]f7022f32014-08-21 16:32:192401 req->Start();
[email protected]255620da2013-08-19 13:14:292402 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442403
2404 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2405 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2406 }
2407
2408 // Verify that the cookie is set.
2409 {
2410 TestNetworkDelegate network_delegate;
2411 default_context_.set_network_delegate(&network_delegate);
2412 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192413 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362414 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192415 req->Start();
[email protected]255620da2013-08-19 13:14:292416 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442417
2418 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2419 != std::string::npos);
2420
2421 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2422 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2423 }
2424
2425 // Verify that the cookie isn't sent.
2426 {
2427 TestNetworkDelegate network_delegate;
2428 default_context_.set_network_delegate(&network_delegate);
2429 TestDelegate d;
2430 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192431 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362432 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192433 req->Start();
[email protected]255620da2013-08-19 13:14:292434 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442435
2436 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2437 == std::string::npos);
2438
[email protected]22e045f2013-09-20 03:54:032439 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442440 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2441 }
2442}
2443
2444TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2445 LocalHttpTestServer test_server;
2446 ASSERT_TRUE(test_server.Start());
2447
2448 // Set up a cookie.
2449 {
2450 TestNetworkDelegate network_delegate;
2451 default_context_.set_network_delegate(&network_delegate);
2452 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192453 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2454 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362455 &d));
[email protected]f7022f32014-08-21 16:32:192456 req->Start();
[email protected]255620da2013-08-19 13:14:292457 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442458
2459 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2460 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2461 }
2462
2463 // Try to set-up another cookie and update the previous cookie.
2464 {
2465 TestNetworkDelegate network_delegate;
2466 default_context_.set_network_delegate(&network_delegate);
2467 TestDelegate d;
2468 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192469 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442470 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362471 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192472 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442473
[email protected]255620da2013-08-19 13:14:292474 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442475
2476 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2477 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2478 }
2479
2480 // Verify the cookies weren't saved or updated.
2481 {
2482 TestNetworkDelegate network_delegate;
2483 default_context_.set_network_delegate(&network_delegate);
2484 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192485 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362486 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192487 req->Start();
[email protected]255620da2013-08-19 13:14:292488 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442489
2490 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2491 == std::string::npos);
2492 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2493 != std::string::npos);
2494
2495 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2496 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2497 }
2498}
2499
2500TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2501 LocalHttpTestServer test_server;
2502 ASSERT_TRUE(test_server.Start());
2503
2504 // Set up an empty cookie.
2505 {
2506 TestNetworkDelegate network_delegate;
2507 default_context_.set_network_delegate(&network_delegate);
2508 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192509 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362510 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192511 req->Start();
[email protected]255620da2013-08-19 13:14:292512 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442513
2514 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2515 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2516 EXPECT_EQ(0, network_delegate.set_cookie_count());
2517 }
2518}
2519
2520TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2521 LocalHttpTestServer test_server;
2522 ASSERT_TRUE(test_server.Start());
2523
2524 // Set up a cookie.
2525 {
2526 TestNetworkDelegate network_delegate;
2527 default_context_.set_network_delegate(&network_delegate);
2528 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192529 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2530 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362531 &d));
[email protected]f7022f32014-08-21 16:32:192532 req->Start();
[email protected]255620da2013-08-19 13:14:292533 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442534
2535 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2536 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2537 }
2538
2539 // Verify that the cookie is set.
2540 {
2541 TestNetworkDelegate network_delegate;
2542 default_context_.set_network_delegate(&network_delegate);
2543 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192544 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362545 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192546 req->Start();
[email protected]255620da2013-08-19 13:14:292547 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442548
2549 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2550 != std::string::npos);
2551
2552 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2553 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2554 }
2555
2556 // Verify that the cookie isn't sent.
2557 {
2558 TestNetworkDelegate network_delegate;
2559 default_context_.set_network_delegate(&network_delegate);
2560 TestDelegate d;
2561 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192562 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362563 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192564 req->Start();
[email protected]255620da2013-08-19 13:14:292565 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442566
2567 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2568 == std::string::npos);
2569
[email protected]22e045f2013-09-20 03:54:032570 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442571 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2572 }
2573}
2574
2575TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2576 LocalHttpTestServer test_server;
2577 ASSERT_TRUE(test_server.Start());
2578
2579 // Set up a cookie.
2580 {
2581 TestNetworkDelegate network_delegate;
2582 default_context_.set_network_delegate(&network_delegate);
2583 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192584 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2585 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362586 &d));
[email protected]f7022f32014-08-21 16:32:192587 req->Start();
[email protected]255620da2013-08-19 13:14:292588 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442589
2590 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2591 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2592 }
2593
2594 // Try to set-up another cookie and update the previous cookie.
2595 {
2596 TestNetworkDelegate network_delegate;
2597 default_context_.set_network_delegate(&network_delegate);
2598 TestDelegate d;
2599 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192600 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442601 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362602 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192603 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442604
[email protected]255620da2013-08-19 13:14:292605 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442606
2607 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2608 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2609 }
2610
2611 // Verify the cookies weren't saved or updated.
2612 {
2613 TestNetworkDelegate network_delegate;
2614 default_context_.set_network_delegate(&network_delegate);
2615 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192616 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362617 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192618 req->Start();
[email protected]255620da2013-08-19 13:14:292619 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442620
2621 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2622 == std::string::npos);
2623 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2624 != std::string::npos);
2625
2626 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2627 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2628 }
2629}
2630
mkwst3f3daac2015-02-26 20:15:262631TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2632 LocalHttpTestServer test_server;
2633 ASSERT_TRUE(test_server.Start());
2634
2635 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2636 // LocalHttpTestServer points).
2637 {
2638 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412639 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262640 default_context_.set_network_delegate(&network_delegate);
2641
2642 TestDelegate d;
2643 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2644 test_server.GetURL(
2645 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
davidben151423e2015-03-23 18:48:362646 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262647 req->Start();
2648 base::RunLoop().Run();
2649 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2650 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2651 EXPECT_EQ(1, network_delegate.set_cookie_count());
2652 }
2653
2654 // Verify that the cookie is sent for first-party requests.
2655 {
2656 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412657 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262658 default_context_.set_network_delegate(&network_delegate);
2659 TestDelegate d;
2660 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362661 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472662 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst3f3daac2015-02-26 20:15:262663 req->Start();
2664 base::RunLoop().Run();
2665
2666 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2667 std::string::npos);
2668 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2669 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2670 }
2671
2672 // Verify that the cookie is not-sent for non-first-party requests.
2673 {
2674 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412675 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262676 default_context_.set_network_delegate(&network_delegate);
2677 TestDelegate d;
2678 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362679 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262680 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2681 req->Start();
2682 base::RunLoop().Run();
2683
2684 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2685 std::string::npos);
2686 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2687 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2688 }
2689}
2690
mkwst0513c9d2015-04-01 05:53:152691TEST_F(URLRequestTest, FirstPartyOnlyCookiesDisabled) {
2692 LocalHttpTestServer test_server;
2693 ASSERT_TRUE(test_server.Start());
2694
2695 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2696 // LocalHttpTestServer points).
2697 {
2698 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412699 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152700 default_context_.set_network_delegate(&network_delegate);
2701
2702 TestDelegate d;
2703 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2704 test_server.GetURL(
2705 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
2706 DEFAULT_PRIORITY, &d));
2707 req->Start();
2708 base::RunLoop().Run();
2709 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2710 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2711 EXPECT_EQ(1, network_delegate.set_cookie_count());
2712 }
2713
2714 // Verify that the cookie is sent for first-party requests.
2715 {
2716 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412717 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152718 default_context_.set_network_delegate(&network_delegate);
2719 TestDelegate d;
2720 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2721 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472722 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst0513c9d2015-04-01 05:53:152723 req->Start();
2724 base::RunLoop().Run();
2725
2726 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2727 std::string::npos);
2728 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2729 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2730 }
2731
2732 // Verify that the cookie is also sent for non-first-party requests.
2733 {
2734 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412735 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152736 default_context_.set_network_delegate(&network_delegate);
2737 TestDelegate d;
2738 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2739 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2740 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2741 req->Start();
2742 base::RunLoop().Run();
2743
2744 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2745 std::string::npos);
2746 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2747 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2748 }
2749}
2750
estarkcd39c11f2015-10-19 19:46:362751// Tests that $Secure- cookies can't be set on non-secure origins.
2752TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
2753 test_server::EmbeddedTestServer test_server;
2754 test_server.RegisterRequestHandler(base::Bind(&HandleSetCookieRequest));
2755 ASSERT_TRUE(test_server.InitializeAndWaitUntilReady());
2756 SpawnedTestServer test_server_https(
2757 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
2758 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2759 ASSERT_TRUE(test_server_https.Start());
2760
2761 TestExperimentalFeaturesNetworkDelegate network_delegate;
2762 TestURLRequestContext context(true);
2763 context.set_network_delegate(&network_delegate);
2764 context.Init();
2765
2766 // Try to set a Secure $Secure- cookie, with experimental features
2767 // enabled.
2768 {
2769 TestDelegate d;
2770 scoped_ptr<URLRequest> req(context.CreateRequest(
2771 test_server.GetURL("/set-cookie?$Secure-nonsecure-origin=1;Secure"),
2772 DEFAULT_PRIORITY, &d));
2773 req->Start();
2774 base::RunLoop().Run();
2775 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2776 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2777 }
2778
2779 // Verify that the cookie is not set.
2780 {
2781 TestDelegate d;
2782 scoped_ptr<URLRequest> req(context.CreateRequest(
2783 test_server_https.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2784 req->Start();
2785 base::RunLoop().Run();
2786
2787 EXPECT_TRUE(d.data_received().find("$Secure-nonsecure-origin=1") ==
2788 std::string::npos);
2789 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2790 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2791 }
2792}
2793
2794TEST_F(URLRequestTest, SecureCookiePrefixNonexperimental) {
2795 SpawnedTestServer test_server(
2796 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
2797 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2798 ASSERT_TRUE(test_server.Start());
2799
2800 TestNetworkDelegate network_delegate;
2801 TestURLRequestContext context(true);
2802 context.set_network_delegate(&network_delegate);
2803 context.Init();
2804
2805 // Without experimental features, there should be no restrictions on
2806 // $Secure- cookies.
2807
2808 // Set a non-Secure cookie with the $Secure- prefix.
2809 {
2810 TestDelegate d;
2811 scoped_ptr<URLRequest> req(context.CreateRequest(
2812 test_server.GetURL("set-cookie?$Secure-nonsecure-not-experimental=1"),
2813 DEFAULT_PRIORITY, &d));
2814 req->Start();
2815 base::RunLoop().Run();
2816 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2817 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2818 }
2819
2820 // Set a Secure cookie with the $Secure- prefix.
2821 {
2822 TestDelegate d;
2823 scoped_ptr<URLRequest> req(context.CreateRequest(
2824 test_server.GetURL(
2825 "set-cookie?$Secure-secure-not-experimental=1;Secure"),
2826 DEFAULT_PRIORITY, &d));
2827 req->Start();
2828 base::RunLoop().Run();
2829 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2830 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2831 }
2832
2833 // Verify that the cookies are set. Neither should have any
2834 // restrictions because the experimental flag is off.
2835 {
2836 TestDelegate d;
2837 scoped_ptr<URLRequest> req(context.CreateRequest(
2838 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2839 req->Start();
2840 base::RunLoop().Run();
2841
2842 EXPECT_TRUE(d.data_received().find("$Secure-secure-not-experimental=1") !=
2843 std::string::npos);
2844 EXPECT_TRUE(
2845 d.data_received().find("$Secure-nonsecure-not-experimental=1") !=
2846 std::string::npos);
2847 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2848 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2849 }
2850}
2851
2852TEST_F(URLRequestTest, SecureCookiePrefixExperimentalNonsecure) {
2853 SpawnedTestServer test_server(
2854 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
2855 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2856 ASSERT_TRUE(test_server.Start());
2857
2858 TestExperimentalFeaturesNetworkDelegate network_delegate;
2859 TestURLRequestContext context(true);
2860 context.set_network_delegate(&network_delegate);
2861 context.Init();
2862
2863 // Try to set a non-Secure $Secure- cookie, with experimental features
2864 // enabled.
2865 {
2866 TestDelegate d;
2867 scoped_ptr<URLRequest> req(context.CreateRequest(
2868 test_server.GetURL("set-cookie?$Secure-foo=1"), DEFAULT_PRIORITY, &d));
2869 req->Start();
2870 base::RunLoop().Run();
2871 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2872 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2873 }
2874
2875 // Verify that the cookie is not set.
2876 {
2877 TestDelegate d;
2878 scoped_ptr<URLRequest> req(context.CreateRequest(
2879 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2880 req->Start();
2881 base::RunLoop().Run();
2882
2883 EXPECT_TRUE(d.data_received().find("$Secure-foo=1") == std::string::npos);
2884 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2885 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2886 }
2887}
2888
2889TEST_F(URLRequestTest, SecureCookiePrefixExperimentalSecure) {
2890 SpawnedTestServer test_server(
2891 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
2892 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2893 ASSERT_TRUE(test_server.Start());
2894
2895 TestExperimentalFeaturesNetworkDelegate network_delegate;
2896 TestURLRequestContext context(true);
2897 context.set_network_delegate(&network_delegate);
2898 context.Init();
2899
2900 // Try to set a Secure $Secure- cookie, with experimental features
2901 // enabled.
2902 {
2903 TestDelegate d;
2904 scoped_ptr<URLRequest> req(context.CreateRequest(
2905 test_server.GetURL("set-cookie?$Secure-bar=1;Secure"), DEFAULT_PRIORITY,
2906 &d));
2907 req->Start();
2908 base::RunLoop().Run();
2909 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2910 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2911 }
2912
2913 // Verify that the cookie is set.
2914 {
2915 TestDelegate d;
2916 scoped_ptr<URLRequest> req(context.CreateRequest(
2917 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2918 req->Start();
2919 base::RunLoop().Run();
2920
2921 EXPECT_TRUE(d.data_received().find("$Secure-bar=1") != std::string::npos);
2922 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2923 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2924 }
2925}
2926
mmenkefb18c772015-09-30 22:22:502927// Tests that a request is cancelled while entering suspend mode. Uses mocks
2928// rather than a spawned test server because the connection used to talk to
2929// the test server is affected by entering suspend mode on Android.
2930TEST_F(URLRequestTest, CancelOnSuspend) {
2931 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
2932 base::PowerMonitor power_monitor(make_scoped_ptr(power_monitor_source));
2933
2934 URLRequestFailedJob::AddUrlHandler();
2935
2936 TestDelegate d;
2937 // Request that just hangs.
2938 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
2939 scoped_ptr<URLRequest> r(
2940 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
2941 r->Start();
2942
2943 power_monitor_source->Suspend();
2944 // Wait for the suspend notification to cause the request to fail.
2945 base::RunLoop().Run();
2946 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
2947 EXPECT_TRUE(d.request_failed());
2948 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2949
2950 URLRequestFilter::GetInstance()->ClearHandlers();
2951
2952 // Shouldn't be needed, but just in case.
2953 power_monitor_source->Resume();
2954}
2955
[email protected]5095cd72012-11-01 10:29:162956// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2957// value for the |fixed_date| argument given to the constructor.
2958class FixedDateNetworkDelegate : public TestNetworkDelegate {
2959 public:
2960 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2961 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:202962 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:162963
[email protected]cba24642014-08-15 20:49:592964 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:202965 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592966 URLRequest* request,
2967 const CompletionCallback& callback,
2968 const HttpResponseHeaders* original_response_headers,
2969 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:132970 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:162971
2972 private:
2973 std::string fixed_date_;
2974
2975 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2976};
2977
2978int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592979 URLRequest* request,
2980 const CompletionCallback& callback,
2981 const HttpResponseHeaders* original_response_headers,
2982 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:162983 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:592984 HttpResponseHeaders* new_response_headers =
2985 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:162986
2987 new_response_headers->RemoveHeader("Date");
2988 new_response_headers->AddHeader("Date: " + fixed_date_);
2989
2990 *override_response_headers = new_response_headers;
2991 return TestNetworkDelegate::OnHeadersReceived(request,
2992 callback,
2993 original_response_headers,
[email protected]5f714132014-03-26 10:41:162994 override_response_headers,
2995 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:162996}
2997
2998// Test that cookie expiration times are adjusted for server/client clock
2999// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3000// headers by defaulting to GMT. (crbug.com/135131)
3001TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3002 LocalHttpTestServer test_server;
3003 ASSERT_TRUE(test_server.Start());
3004
3005 // Set up an expired cookie.
3006 {
3007 TestNetworkDelegate network_delegate;
3008 default_context_.set_network_delegate(&network_delegate);
3009 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193010 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193011 test_server.GetURL(
3012 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363013 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193014 req->Start();
[email protected]255620da2013-08-19 13:14:293015 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163016 }
3017 // Verify that the cookie is not set.
3018 {
3019 TestNetworkDelegate network_delegate;
3020 default_context_.set_network_delegate(&network_delegate);
3021 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193022 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363023 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193024 req->Start();
[email protected]255620da2013-08-19 13:14:293025 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163026
3027 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3028 }
3029 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3030 {
3031 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3032 default_context_.set_network_delegate(&network_delegate);
3033 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193034 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193035 test_server.GetURL(
3036 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363037 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193038 req->Start();
[email protected]255620da2013-08-19 13:14:293039 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163040 }
3041 // Verify that the cookie is set.
3042 {
3043 TestNetworkDelegate network_delegate;
3044 default_context_.set_network_delegate(&network_delegate);
3045 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193046 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363047 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193048 req->Start();
[email protected]255620da2013-08-19 13:14:293049 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163050
3051 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3052 }
3053}
3054
3055
[email protected]316c1e5e2012-09-12 15:17:443056// Check that it is impossible to change the referrer in the extra headers of
3057// an URLRequest.
3058TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3059 LocalHttpTestServer test_server;
3060 ASSERT_TRUE(test_server.Start());
3061
3062 // If extra headers contain referer and the request contains a referer,
3063 // only the latter shall be respected.
3064 {
3065 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193066 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363067 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193068 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443069
3070 HttpRequestHeaders headers;
3071 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193072 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443073
[email protected]f7022f32014-08-21 16:32:193074 req->Start();
[email protected]255620da2013-08-19 13:14:293075 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443076
3077 EXPECT_EQ("http://foo.com/", d.data_received());
3078 }
3079
3080 // If extra headers contain a referer but the request does not, no referer
3081 // shall be sent in the header.
3082 {
3083 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193084 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363085 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443086
3087 HttpRequestHeaders headers;
3088 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193089 req->SetExtraRequestHeaders(headers);
3090 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443091
[email protected]f7022f32014-08-21 16:32:193092 req->Start();
[email protected]255620da2013-08-19 13:14:293093 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443094
3095 EXPECT_EQ("None", d.data_received());
3096 }
3097}
3098
[email protected]b89290212009-08-14 22:37:353099class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113100 public:
mmenke9f2ec60c2015-06-01 20:59:473101 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113102
[email protected]b89290212009-08-14 22:37:353103 protected:
[email protected]21184962011-10-26 00:50:303104 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3105 // |request_method| is the method to use for the initial request.
3106 // |redirect_method| is the method that is expected to be used for the second
3107 // request, after redirection.
3108 // If |include_data| is true, data is uploaded with the request. The
3109 // response body is expected to match it exactly, if and only if
3110 // |request_method| == |redirect_method|.
3111 void HTTPRedirectMethodTest(const GURL& redirect_url,
3112 const std::string& request_method,
3113 const std::string& redirect_method,
3114 bool include_data) {
3115 static const char kData[] = "hello world";
3116 TestDelegate d;
davidben151423e2015-03-23 18:48:363117 scoped_ptr<URLRequest> req(
3118 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193119 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303120 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073121 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303122 HttpRequestHeaders headers;
3123 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513124 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543125 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193126 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303127 }
[email protected]f7022f32014-08-21 16:32:193128 req->Start();
[email protected]255620da2013-08-19 13:14:293129 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193130 EXPECT_EQ(redirect_method, req->method());
3131 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
3132 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:303133 if (include_data) {
3134 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543135 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3136 HttpRequestHeaders::kContentLength));
3137 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3138 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303139 EXPECT_EQ(kData, d.data_received());
3140 } else {
svaldez5b3a8972015-10-09 23:23:543141 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3142 HttpRequestHeaders::kContentLength));
3143 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3144 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303145 EXPECT_NE(kData, d.data_received());
3146 }
3147 }
3148 if (HasFailure())
3149 LOG(WARNING) << "Request method was: " << request_method;
3150 }
3151
jww5fe460ff2015-03-28 00:22:513152 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3153 // |request_method| is the method to use for the initial request.
3154 // |redirect_method| is the method that is expected to be used for the second
3155 // request, after redirection.
3156 // |origin_value| is the expected value for the Origin header after
3157 // redirection. If empty, expects that there will be no Origin header.
3158 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3159 const std::string& request_method,
3160 const std::string& redirect_method,
3161 const std::string& origin_value) {
3162 TestDelegate d;
3163 scoped_ptr<URLRequest> req(
3164 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3165 req->set_method(request_method);
3166 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3167 redirect_url.GetOrigin().spec(), false);
3168 req->Start();
3169
3170 base::RunLoop().Run();
3171
3172 EXPECT_EQ(redirect_method, req->method());
3173 // Note that there is no check for request success here because, for
3174 // purposes of testing, the request very well may fail. For example, if the
3175 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3176 // origin, there is not an HTTPS server in this unit test framework, so the
3177 // request would fail. However, that's fine, as long as the request headers
3178 // are in order and pass the checks below.
3179 if (origin_value.empty()) {
3180 EXPECT_FALSE(
3181 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3182 } else {
3183 std::string origin_header;
3184 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3185 HttpRequestHeaders::kOrigin, &origin_header));
3186 EXPECT_EQ(origin_value, origin_header);
3187 }
3188 }
3189
[email protected]762d2db2010-01-11 19:03:013190 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013191 const int kMsgSize = 20000; // multiple of 10
3192 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483193 char* uploadBytes = new char[kMsgSize+1];
3194 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013195 char marker = 'a';
3196 for (int idx = 0; idx < kMsgSize/10; idx++) {
3197 memcpy(ptr, "----------", 10);
3198 ptr += 10;
3199 if (idx % 100 == 0) {
3200 ptr--;
3201 *ptr++ = marker;
3202 if (++marker > 'z')
3203 marker = 'a';
3204 }
3205 }
3206 uploadBytes[kMsgSize] = '\0';
3207
[email protected]762d2db2010-01-11 19:03:013208 for (int i = 0; i < kIterations; ++i) {
3209 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193210 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363211 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193212 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013213
mmenkecbc2b712014-10-09 20:29:073214 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013215
[email protected]f7022f32014-08-21 16:32:193216 r->Start();
3217 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013218
[email protected]255620da2013-08-19 13:14:293219 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013220
[email protected]329b68b2012-11-14 17:54:273221 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:193222 << "request failed: " << r->status().status()
3223 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:013224
3225 EXPECT_FALSE(d.received_data_before_response());
3226 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013227 }
3228 delete[] uploadBytes;
3229 }
3230
[email protected]ef2bf422012-05-11 03:27:093231 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:223232 r->AppendChunkToUpload("a", 1, false);
3233 r->AppendChunkToUpload("bcd", 3, false);
3234 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
3235 r->AppendChunkToUpload("\r\n\r\n", 4, false);
3236 r->AppendChunkToUpload("0", 1, false);
3237 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:113238 }
3239
[email protected]ef2bf422012-05-11 03:27:093240 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:113241 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:273242 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:113243 "abcdthis is a longer chunk than before.\r\n\r\n02323";
3244
[email protected]329b68b2012-11-14 17:54:273245 ASSERT_EQ(1, d->response_started_count())
3246 << "request failed: " << r->status().status()
3247 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:113248
3249 EXPECT_FALSE(d->received_data_before_response());
3250
[email protected]329b68b2012-11-14 17:54:273251 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
3252 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:113253 }
3254
[email protected]ede03212012-09-07 12:52:263255 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343256 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193257 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3258 test_server_.GetURL("set-many-cookies?" +
davidben151423e2015-03-23 18:48:363259 base::IntToString(num_cookies)),
3260 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343261
[email protected]f7022f32014-08-21 16:32:193262 r->Start();
3263 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343264
[email protected]255620da2013-08-19 13:14:293265 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343266
[email protected]f7022f32014-08-21 16:32:193267 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:343268
[email protected]ede03212012-09-07 12:52:263269 if (!is_success) {
[email protected]f7022f32014-08-21 16:32:193270 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:343271 // The test server appears to be unable to handle subsequent requests
3272 // after this error is triggered. Force it to restart.
3273 EXPECT_TRUE(test_server_.Stop());
3274 EXPECT_TRUE(test_server_.Start());
3275 }
3276
3277 return is_success;
3278 }
3279
bengr1bf8e942014-11-07 01:36:503280 LocalHttpTestServer* test_server() {
3281 return &test_server_;
3282 }
3283
3284 protected:
[email protected]1700c6a2012-02-22 18:07:073285 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353286};
3287
[email protected]95409e12010-08-17 20:07:113288// In this unit test, we're using the HTTPTestServer as a proxy server and
3289// issuing a CONNECT request with the magic host name "www.redirect.com".
3290// The HTTPTestServer will return a 302 response, which we should not
3291// follow.
[email protected]f2f31b32013-01-16 23:24:093292TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:113293 ASSERT_TRUE(test_server_.Start());
3294
[email protected]ceefd7fd2012-11-29 00:36:243295 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043296 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193297 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503298
[email protected]d1ec59082009-02-11 02:48:153299 TestDelegate d;
3300 {
[email protected]f7022f32014-08-21 16:32:193301 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363302 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193303 r->Start();
3304 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153305
[email protected]255620da2013-08-19 13:14:293306 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153307
[email protected]f7022f32014-08-21 16:32:193308 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153309 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193310 EXPECT_TRUE(r->proxy_server().IsEmpty());
3311 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083312 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153313 // We should not have followed the redirect.
3314 EXPECT_EQ(0, d.received_redirect_count());
3315 }
3316}
3317
[email protected]8202d0c2011-02-23 08:31:143318// This is the same as the previous test, but checks that the network delegate
3319// registers the error.
[email protected]c044616e2013-02-20 02:01:263320TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:143321 ASSERT_TRUE(test_server_.Start());
3322
[email protected]ceefd7fd2012-11-29 00:36:243323 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043324 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193325 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503326
[email protected]8202d0c2011-02-23 08:31:143327 TestDelegate d;
3328 {
[email protected]f7022f32014-08-21 16:32:193329 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363330 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193331 r->Start();
3332 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143333
[email protected]255620da2013-08-19 13:14:293334 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143335
[email protected]f7022f32014-08-21 16:32:193336 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153337 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193338 EXPECT_TRUE(r->proxy_server().IsEmpty());
3339 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143340 EXPECT_EQ(1, d.response_started_count());
3341 // We should not have followed the redirect.
3342 EXPECT_EQ(0, d.received_redirect_count());
3343
3344 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053345 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143346 }
3347}
3348
[email protected]dc5a5cf2012-09-26 02:49:303349// Tests that we can block and asynchronously return OK in various stages.
3350TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3351 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3352 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3353 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3354 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3355 };
3356 static const size_t blocking_stages_length = arraysize(blocking_stages);
3357
3358 ASSERT_TRUE(test_server_.Start());
3359
3360 TestDelegate d;
3361 BlockingNetworkDelegate network_delegate(
3362 BlockingNetworkDelegate::USER_CALLBACK);
3363 network_delegate.set_block_on(
3364 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3365 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3366 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3367
3368 TestURLRequestContext context(true);
3369 context.set_network_delegate(&network_delegate);
3370 context.Init();
3371
3372 {
[email protected]f7022f32014-08-21 16:32:193373 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363374 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303375
[email protected]f7022f32014-08-21 16:32:193376 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303377 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293378 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303379 EXPECT_EQ(blocking_stages[i],
3380 network_delegate.stage_blocked_for_callback());
3381 network_delegate.DoCallback(OK);
3382 }
[email protected]255620da2013-08-19 13:14:293383 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193384 EXPECT_EQ(200, r->GetResponseCode());
3385 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303386 EXPECT_EQ(1, network_delegate.created_requests());
3387 EXPECT_EQ(0, network_delegate.destroyed_requests());
3388 }
3389 EXPECT_EQ(1, network_delegate.destroyed_requests());
3390}
3391
[email protected]4c76d7c2011-04-15 19:14:123392// Tests that the network delegate can block and cancel a request.
3393TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
3394 ASSERT_TRUE(test_server_.Start());
3395
3396 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303397 BlockingNetworkDelegate network_delegate(
3398 BlockingNetworkDelegate::AUTO_CALLBACK);
3399 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3400 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123401
[email protected]d5a4dd62012-05-23 01:41:043402 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193403 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503404
[email protected]4c76d7c2011-04-15 19:14:123405 {
[email protected]f7022f32014-08-21 16:32:193406 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363407 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123408
[email protected]f7022f32014-08-21 16:32:193409 r->Start();
[email protected]255620da2013-08-19 13:14:293410 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123411
[email protected]f7022f32014-08-21 16:32:193412 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153413 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193414 EXPECT_TRUE(r->proxy_server().IsEmpty());
3415 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123416 EXPECT_EQ(1, network_delegate.created_requests());
3417 EXPECT_EQ(0, network_delegate.destroyed_requests());
3418 }
3419 EXPECT_EQ(1, network_delegate.destroyed_requests());
3420}
3421
[email protected]b4438d32012-09-27 06:15:303422// Helper function for NetworkDelegateCancelRequestAsynchronously and
3423// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3424// delegate operating in |block_mode| and a request for |url|. It blocks the
3425// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3426void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3427 BlockingNetworkDelegate::Stage stage,
3428 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363429 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303430 BlockingNetworkDelegate network_delegate(block_mode);
3431 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3432 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363433
[email protected]b4438d32012-09-27 06:15:303434 TestURLRequestContext context(true);
3435 context.set_network_delegate(&network_delegate);
3436 context.Init();
[email protected]3cd384c602011-08-31 16:12:363437
3438 {
davidben151423e2015-03-23 18:48:363439 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363440
[email protected]f7022f32014-08-21 16:32:193441 r->Start();
[email protected]255620da2013-08-19 13:14:293442 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363443
[email protected]f7022f32014-08-21 16:32:193444 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153445 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193446 EXPECT_TRUE(r->proxy_server().IsEmpty());
3447 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363448 EXPECT_EQ(1, network_delegate.created_requests());
3449 EXPECT_EQ(0, network_delegate.destroyed_requests());
3450 }
3451 EXPECT_EQ(1, network_delegate.destroyed_requests());
3452}
3453
[email protected]b4438d32012-09-27 06:15:303454// The following 3 tests check that the network delegate can cancel a request
3455// synchronously in various stages of the request.
3456TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
3457 ASSERT_TRUE(test_server_.Start());
3458 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3459 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453460 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303461}
3462
3463TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
3464 ASSERT_TRUE(test_server_.Start());
3465 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3466 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453467 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303468}
3469
3470TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
3471 ASSERT_TRUE(test_server_.Start());
3472 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3473 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453474 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303475}
3476
3477// The following 3 tests check that the network delegate can cancel a request
3478// asynchronously in various stages of the request.
3479TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
3480 ASSERT_TRUE(test_server_.Start());
3481 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3482 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453483 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303484}
3485
3486TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
3487 ASSERT_TRUE(test_server_.Start());
3488 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3489 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453490 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303491}
3492
3493TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
3494 ASSERT_TRUE(test_server_.Start());
3495 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3496 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453497 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303498}
3499
[email protected]4c76d7c2011-04-15 19:14:123500// Tests that the network delegate can block and redirect a request to a new
3501// URL.
3502TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
3503 ASSERT_TRUE(test_server_.Start());
3504
3505 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303506 BlockingNetworkDelegate network_delegate(
3507 BlockingNetworkDelegate::AUTO_CALLBACK);
3508 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:123509 GURL redirect_url(test_server_.GetURL("simple.html"));
3510 network_delegate.set_redirect_url(redirect_url);
3511
[email protected]d5a4dd62012-05-23 01:41:043512 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193513 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503514
[email protected]4c76d7c2011-04-15 19:14:123515 {
[email protected]8f1ac082011-04-19 21:14:133516 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363517 scoped_ptr<URLRequest> r(
3518 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123519
[email protected]6be6fa92014-08-06 23:44:563520 // Quit after hitting the redirect, so can check the headers.
3521 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193522 r->Start();
[email protected]255620da2013-08-19 13:14:293523 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123524
[email protected]6be6fa92014-08-06 23:44:563525 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193526 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3527 EXPECT_EQ(307, r->GetResponseCode());
3528 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563529 std::string location;
[email protected]f7022f32014-08-21 16:32:193530 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3531 &location));
[email protected]6be6fa92014-08-06 23:44:563532 EXPECT_EQ(redirect_url, GURL(location));
3533
3534 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193535 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563536 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193537 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3538 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273539 EXPECT_EQ(
3540 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3541 EXPECT_TRUE(
3542 network_delegate.last_observed_proxy().Equals(
3543 test_server_.host_port_pair()));
3544
[email protected]f7022f32014-08-21 16:32:193545 EXPECT_EQ(0, r->status().error());
3546 EXPECT_EQ(redirect_url, r->url());
3547 EXPECT_EQ(original_url, r->original_url());
3548 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123549 EXPECT_EQ(1, network_delegate.created_requests());
3550 EXPECT_EQ(0, network_delegate.destroyed_requests());
3551 }
3552 EXPECT_EQ(1, network_delegate.destroyed_requests());
3553}
3554
[email protected]b813ed72012-04-05 08:21:363555// Tests that the network delegate can block and redirect a request to a new
3556// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3557TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
3558 ASSERT_TRUE(test_server_.Start());
3559
3560 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303561 BlockingNetworkDelegate network_delegate(
3562 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:363563 GURL redirect_url(test_server_.GetURL("simple.html"));
3564 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363565
[email protected]d5a4dd62012-05-23 01:41:043566 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193567 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363568
3569 {
3570 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363571 scoped_ptr<URLRequest> r(
3572 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363573
[email protected]6be6fa92014-08-06 23:44:563574 // Quit after hitting the redirect, so can check the headers.
3575 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193576 r->Start();
[email protected]255620da2013-08-19 13:14:293577 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363578
[email protected]6be6fa92014-08-06 23:44:563579 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193580 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3581 EXPECT_EQ(307, r->GetResponseCode());
3582 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563583 std::string location;
[email protected]f7022f32014-08-21 16:32:193584 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3585 &location));
[email protected]6be6fa92014-08-06 23:44:563586 EXPECT_EQ(redirect_url, GURL(location));
3587
3588 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193589 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563590 base::RunLoop().Run();
3591
[email protected]f7022f32014-08-21 16:32:193592 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3593 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273594 EXPECT_EQ(
3595 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3596 EXPECT_TRUE(
3597 network_delegate.last_observed_proxy().Equals(
3598 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193599 EXPECT_EQ(0, r->status().error());
3600 EXPECT_EQ(redirect_url, r->url());
3601 EXPECT_EQ(original_url, r->original_url());
3602 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363603 EXPECT_EQ(1, network_delegate.created_requests());
3604 EXPECT_EQ(0, network_delegate.destroyed_requests());
3605 }
3606 EXPECT_EQ(1, network_delegate.destroyed_requests());
3607}
3608
[email protected]3c5ca8c2011-09-29 01:14:513609// Tests that redirects caused by the network delegate preserve POST data.
3610TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3611 ASSERT_TRUE(test_server_.Start());
3612
3613 const char kData[] = "hello world";
3614
3615 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303616 BlockingNetworkDelegate network_delegate(
3617 BlockingNetworkDelegate::AUTO_CALLBACK);
3618 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:513619 GURL redirect_url(test_server_.GetURL("echo"));
3620 network_delegate.set_redirect_url(redirect_url);
3621
[email protected]ef2bf422012-05-11 03:27:093622 TestURLRequestContext context(true);
3623 context.set_network_delegate(&network_delegate);
3624 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513625
3626 {
3627 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363628 scoped_ptr<URLRequest> r(
3629 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193630 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073631 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513632 HttpRequestHeaders headers;
3633 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513634 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193635 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563636
3637 // Quit after hitting the redirect, so can check the headers.
3638 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193639 r->Start();
[email protected]255620da2013-08-19 13:14:293640 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513641
[email protected]6be6fa92014-08-06 23:44:563642 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193643 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3644 EXPECT_EQ(307, r->GetResponseCode());
3645 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563646 std::string location;
[email protected]f7022f32014-08-21 16:32:193647 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3648 &location));
[email protected]6be6fa92014-08-06 23:44:563649 EXPECT_EQ(redirect_url, GURL(location));
3650
3651 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193652 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563653 base::RunLoop().Run();
3654
[email protected]f7022f32014-08-21 16:32:193655 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3656 EXPECT_EQ(0, r->status().error());
3657 EXPECT_EQ(redirect_url, r->url());
3658 EXPECT_EQ(original_url, r->original_url());
3659 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513660 EXPECT_EQ(1, network_delegate.created_requests());
3661 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193662 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513663 EXPECT_EQ(kData, d.data_received());
3664 }
3665 EXPECT_EQ(1, network_delegate.destroyed_requests());
3666}
3667
[email protected]5f714132014-03-26 10:41:163668// Tests that the network delegate can block and redirect a request to a new
3669// URL during OnHeadersReceived.
3670TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3671 ASSERT_TRUE(test_server_.Start());
3672
3673 TestDelegate d;
3674 BlockingNetworkDelegate network_delegate(
3675 BlockingNetworkDelegate::AUTO_CALLBACK);
3676 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3677 GURL redirect_url(test_server_.GetURL("simple.html"));
3678 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3679
3680 TestURLRequestContextWithProxy context(
3681 test_server_.host_port_pair().ToString(), &network_delegate);
3682
3683 {
3684 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363685 scoped_ptr<URLRequest> r(
3686 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163687
[email protected]f7022f32014-08-21 16:32:193688 r->Start();
[email protected]5f714132014-03-26 10:41:163689 base::RunLoop().Run();
3690
[email protected]f7022f32014-08-21 16:32:193691 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3692 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273693 EXPECT_EQ(
3694 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3695 EXPECT_TRUE(
3696 network_delegate.last_observed_proxy().Equals(
3697 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193698
3699 EXPECT_EQ(OK, r->status().error());
3700 EXPECT_EQ(redirect_url, r->url());
3701 EXPECT_EQ(original_url, r->original_url());
3702 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163703 EXPECT_EQ(2, network_delegate.created_requests());
3704 EXPECT_EQ(0, network_delegate.destroyed_requests());
3705 }
3706 EXPECT_EQ(1, network_delegate.destroyed_requests());
3707}
3708
[email protected]c2911d72011-10-03 22:16:363709// Tests that the network delegate can synchronously complete OnAuthRequired
3710// by taking no action. This indicates that the NetworkDelegate does not want to
3711// handle the challenge, and is passing the buck along to the
3712// URLRequest::Delegate.
3713TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3714 ASSERT_TRUE(test_server_.Start());
3715
3716 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303717 BlockingNetworkDelegate network_delegate(
3718 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363719
[email protected]ef2bf422012-05-11 03:27:093720 TestURLRequestContext context(true);
3721 context.set_network_delegate(&network_delegate);
3722 context.Init();
[email protected]c2911d72011-10-03 22:16:363723
[email protected]f3cf9802011-10-28 18:44:583724 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363725
3726 {
3727 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363728 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193729 r->Start();
[email protected]79e1fd62013-06-20 06:50:043730
[email protected]255620da2013-08-19 13:14:293731 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043732
[email protected]f7022f32014-08-21 16:32:193733 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3734 EXPECT_EQ(0, r->status().error());
3735 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043736 EXPECT_TRUE(d.auth_required_called());
3737 EXPECT_EQ(1, network_delegate.created_requests());
3738 EXPECT_EQ(0, network_delegate.destroyed_requests());
3739 }
3740 EXPECT_EQ(1, network_delegate.destroyed_requests());
3741}
3742
3743TEST_F(URLRequestTestHTTP,
3744 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3745 ASSERT_TRUE(test_server_.Start());
3746
3747 TestDelegate d;
3748 BlockingNetworkDelegate network_delegate(
3749 BlockingNetworkDelegate::SYNCHRONOUS);
3750
3751 TestURLRequestContext context(true);
3752 context.set_network_delegate(&network_delegate);
3753 context.Init();
3754
3755 d.set_credentials(AuthCredentials(kUser, kSecret));
3756
3757 {
3758 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363759 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193760 r->Start();
[email protected]79e1fd62013-06-20 06:50:043761
3762 {
3763 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193764 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043765 EXPECT_FALSE(headers.HasHeader("Authorization"));
3766 }
3767
[email protected]255620da2013-08-19 13:14:293768 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363769
[email protected]f7022f32014-08-21 16:32:193770 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3771 EXPECT_EQ(0, r->status().error());
3772 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363773 EXPECT_TRUE(d.auth_required_called());
3774 EXPECT_EQ(1, network_delegate.created_requests());
3775 EXPECT_EQ(0, network_delegate.destroyed_requests());
3776 }
3777 EXPECT_EQ(1, network_delegate.destroyed_requests());
3778}
3779
3780// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403781// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363782TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3783 ASSERT_TRUE(test_server_.Start());
3784
3785 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303786 BlockingNetworkDelegate network_delegate(
3787 BlockingNetworkDelegate::SYNCHRONOUS);
3788 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363789 network_delegate.set_auth_retval(
3790 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3791
[email protected]f3cf9802011-10-28 18:44:583792 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363793
[email protected]ef2bf422012-05-11 03:27:093794 TestURLRequestContext context(true);
3795 context.set_network_delegate(&network_delegate);
3796 context.Init();
[email protected]c2911d72011-10-03 22:16:363797
3798 {
3799 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363800 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193801 r->Start();
[email protected]255620da2013-08-19 13:14:293802 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363803
[email protected]f7022f32014-08-21 16:32:193804 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3805 EXPECT_EQ(0, r->status().error());
3806 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363807 EXPECT_FALSE(d.auth_required_called());
3808 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
[email protected]79e1fd62013-06-20 06:50:043814// Same as above, but also tests that GetFullRequestHeaders returns the proper
3815// headers (for the first or second request) when called at the proper times.
3816TEST_F(URLRequestTestHTTP,
3817 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3818 ASSERT_TRUE(test_server_.Start());
3819
3820 TestDelegate d;
3821 BlockingNetworkDelegate network_delegate(
3822 BlockingNetworkDelegate::SYNCHRONOUS);
3823 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3824 network_delegate.set_auth_retval(
3825 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3826
3827 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3828
3829 TestURLRequestContext context(true);
3830 context.set_network_delegate(&network_delegate);
3831 context.Init();
3832
3833 {
3834 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363835 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193836 r->Start();
[email protected]255620da2013-08-19 13:14:293837 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043838
[email protected]f7022f32014-08-21 16:32:193839 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3840 EXPECT_EQ(0, r->status().error());
3841 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043842 EXPECT_FALSE(d.auth_required_called());
3843 EXPECT_EQ(1, network_delegate.created_requests());
3844 EXPECT_EQ(0, network_delegate.destroyed_requests());
3845
3846 {
3847 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193848 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043849 EXPECT_TRUE(headers.HasHeader("Authorization"));
3850 }
3851 }
3852 EXPECT_EQ(1, network_delegate.destroyed_requests());
3853}
3854
[email protected]c2911d72011-10-03 22:16:363855// Tests that the network delegate can synchronously complete OnAuthRequired
3856// by cancelling authentication.
3857TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3858 ASSERT_TRUE(test_server_.Start());
3859
3860 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303861 BlockingNetworkDelegate network_delegate(
3862 BlockingNetworkDelegate::SYNCHRONOUS);
3863 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363864 network_delegate.set_auth_retval(
3865 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3866
[email protected]ef2bf422012-05-11 03:27:093867 TestURLRequestContext context(true);
3868 context.set_network_delegate(&network_delegate);
3869 context.Init();
[email protected]c2911d72011-10-03 22:16:363870
3871 {
3872 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363873 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193874 r->Start();
[email protected]255620da2013-08-19 13:14:293875 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363876
[email protected]f7022f32014-08-21 16:32:193877 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3878 EXPECT_EQ(OK, r->status().error());
3879 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363880 EXPECT_FALSE(d.auth_required_called());
3881 EXPECT_EQ(1, network_delegate.created_requests());
3882 EXPECT_EQ(0, network_delegate.destroyed_requests());
3883 }
3884 EXPECT_EQ(1, network_delegate.destroyed_requests());
3885}
3886
3887// Tests that the network delegate can asynchronously complete OnAuthRequired
3888// by taking no action. This indicates that the NetworkDelegate does not want
3889// to handle the challenge, and is passing the buck along to the
3890// URLRequest::Delegate.
3891TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3892 ASSERT_TRUE(test_server_.Start());
3893
3894 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303895 BlockingNetworkDelegate network_delegate(
3896 BlockingNetworkDelegate::AUTO_CALLBACK);
3897 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363898
[email protected]ef2bf422012-05-11 03:27:093899 TestURLRequestContext context(true);
3900 context.set_network_delegate(&network_delegate);
3901 context.Init();
[email protected]c2911d72011-10-03 22:16:363902
[email protected]f3cf9802011-10-28 18:44:583903 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363904
3905 {
3906 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363907 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193908 r->Start();
[email protected]255620da2013-08-19 13:14:293909 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363910
[email protected]f7022f32014-08-21 16:32:193911 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3912 EXPECT_EQ(0, r->status().error());
3913 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363914 EXPECT_TRUE(d.auth_required_called());
3915 EXPECT_EQ(1, network_delegate.created_requests());
3916 EXPECT_EQ(0, network_delegate.destroyed_requests());
3917 }
3918 EXPECT_EQ(1, network_delegate.destroyed_requests());
3919}
3920
3921// Tests that the network delegate can asynchronously complete OnAuthRequired
3922// by setting credentials.
3923TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3924 ASSERT_TRUE(test_server_.Start());
3925
3926 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303927 BlockingNetworkDelegate network_delegate(
3928 BlockingNetworkDelegate::AUTO_CALLBACK);
3929 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363930 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363931 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3932
[email protected]f3cf9802011-10-28 18:44:583933 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363934 network_delegate.set_auth_credentials(auth_credentials);
3935
[email protected]ef2bf422012-05-11 03:27:093936 TestURLRequestContext context(true);
3937 context.set_network_delegate(&network_delegate);
3938 context.Init();
[email protected]c2911d72011-10-03 22:16:363939
3940 {
3941 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363942 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193943 r->Start();
[email protected]255620da2013-08-19 13:14:293944 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363945
[email protected]f7022f32014-08-21 16:32:193946 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3947 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:363948
[email protected]f7022f32014-08-21 16:32:193949 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363950 EXPECT_FALSE(d.auth_required_called());
3951 EXPECT_EQ(1, network_delegate.created_requests());
3952 EXPECT_EQ(0, network_delegate.destroyed_requests());
3953 }
3954 EXPECT_EQ(1, network_delegate.destroyed_requests());
3955}
3956
3957// Tests that the network delegate can asynchronously complete OnAuthRequired
3958// by cancelling authentication.
3959TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3960 ASSERT_TRUE(test_server_.Start());
3961
3962 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303963 BlockingNetworkDelegate network_delegate(
3964 BlockingNetworkDelegate::AUTO_CALLBACK);
3965 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363966 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363967 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3968
[email protected]ef2bf422012-05-11 03:27:093969 TestURLRequestContext context(true);
3970 context.set_network_delegate(&network_delegate);
3971 context.Init();
[email protected]c2911d72011-10-03 22:16:363972
3973 {
3974 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363975 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193976 r->Start();
[email protected]255620da2013-08-19 13:14:293977 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363978
[email protected]f7022f32014-08-21 16:32:193979 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3980 EXPECT_EQ(OK, r->status().error());
3981 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363982 EXPECT_FALSE(d.auth_required_called());
3983 EXPECT_EQ(1, network_delegate.created_requests());
3984 EXPECT_EQ(0, network_delegate.destroyed_requests());
3985 }
3986 EXPECT_EQ(1, network_delegate.destroyed_requests());
3987}
3988
[email protected]9045b8822012-01-13 20:35:353989// Tests that we can handle when a network request was canceled while we were
3990// waiting for the network delegate.
3991// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3992TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3993 ASSERT_TRUE(test_server_.Start());
3994
3995 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303996 BlockingNetworkDelegate network_delegate(
3997 BlockingNetworkDelegate::USER_CALLBACK);
3998 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353999
[email protected]ef2bf422012-05-11 03:27:094000 TestURLRequestContext context(true);
4001 context.set_network_delegate(&network_delegate);
4002 context.Init();
[email protected]9045b8822012-01-13 20:35:354003
4004 {
[email protected]f7022f32014-08-21 16:32:194005 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364006 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354007
[email protected]f7022f32014-08-21 16:32:194008 r->Start();
[email protected]255620da2013-08-19 13:14:294009 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304010 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4011 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354012 EXPECT_EQ(0, network_delegate.completed_requests());
4013 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194014 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354015 // Ensure that network delegate is notified.
4016 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194017 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4018 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354019 EXPECT_EQ(1, network_delegate.created_requests());
4020 EXPECT_EQ(0, network_delegate.destroyed_requests());
4021 }
4022 EXPECT_EQ(1, network_delegate.destroyed_requests());
4023}
4024
4025// Tests that we can handle when a network request was canceled while we were
4026// waiting for the network delegate.
4027// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
4028TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
4029 ASSERT_TRUE(test_server_.Start());
4030
4031 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304032 BlockingNetworkDelegate network_delegate(
4033 BlockingNetworkDelegate::USER_CALLBACK);
4034 network_delegate.set_block_on(
4035 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354036
[email protected]ef2bf422012-05-11 03:27:094037 TestURLRequestContext context(true);
4038 context.set_network_delegate(&network_delegate);
4039 context.Init();
[email protected]9045b8822012-01-13 20:35:354040
4041 {
[email protected]f7022f32014-08-21 16:32:194042 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364043 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354044
[email protected]f7022f32014-08-21 16:32:194045 r->Start();
[email protected]255620da2013-08-19 13:14:294046 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304047 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4048 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354049 EXPECT_EQ(0, network_delegate.completed_requests());
4050 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194051 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354052 // Ensure that network delegate is notified.
4053 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194054 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4055 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354056 EXPECT_EQ(1, network_delegate.created_requests());
4057 EXPECT_EQ(0, network_delegate.destroyed_requests());
4058 }
4059 EXPECT_EQ(1, network_delegate.destroyed_requests());
4060}
4061
4062// Tests that we can handle when a network request was canceled while we were
4063// waiting for the network delegate.
4064// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4065TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
4066 ASSERT_TRUE(test_server_.Start());
4067
4068 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304069 BlockingNetworkDelegate network_delegate(
4070 BlockingNetworkDelegate::USER_CALLBACK);
4071 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354072
[email protected]ef2bf422012-05-11 03:27:094073 TestURLRequestContext context(true);
4074 context.set_network_delegate(&network_delegate);
4075 context.Init();
[email protected]9045b8822012-01-13 20:35:354076
4077 {
[email protected]f7022f32014-08-21 16:32:194078 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364079 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354080
[email protected]f7022f32014-08-21 16:32:194081 r->Start();
[email protected]255620da2013-08-19 13:14:294082 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304083 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4084 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354085 EXPECT_EQ(0, network_delegate.completed_requests());
4086 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194087 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354088 // Ensure that network delegate is notified.
4089 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194090 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4091 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354092 EXPECT_EQ(1, network_delegate.created_requests());
4093 EXPECT_EQ(0, network_delegate.destroyed_requests());
4094 }
4095 EXPECT_EQ(1, network_delegate.destroyed_requests());
4096}
4097
4098// Tests that we can handle when a network request was canceled while we were
4099// waiting for the network delegate.
4100// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024101TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:354102 ASSERT_TRUE(test_server_.Start());
4103
4104 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304105 BlockingNetworkDelegate network_delegate(
4106 BlockingNetworkDelegate::USER_CALLBACK);
4107 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354108
[email protected]ef2bf422012-05-11 03:27:094109 TestURLRequestContext context(true);
4110 context.set_network_delegate(&network_delegate);
4111 context.Init();
[email protected]9045b8822012-01-13 20:35:354112
4113 {
[email protected]f7022f32014-08-21 16:32:194114 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364115 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354116
[email protected]f7022f32014-08-21 16:32:194117 r->Start();
[email protected]255620da2013-08-19 13:14:294118 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304119 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4120 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354121 EXPECT_EQ(0, network_delegate.completed_requests());
4122 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194123 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354124 // Ensure that network delegate is notified.
4125 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194126 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4127 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354128 EXPECT_EQ(1, network_delegate.created_requests());
4129 EXPECT_EQ(0, network_delegate.destroyed_requests());
4130 }
4131 EXPECT_EQ(1, network_delegate.destroyed_requests());
4132}
4133
[email protected]95409e12010-08-17 20:07:114134// In this unit test, we're using the HTTPTestServer as a proxy server and
4135// issuing a CONNECT request with the magic host name "www.server-auth.com".
4136// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354137TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:114138 ASSERT_TRUE(test_server_.Start());
4139
[email protected]ceefd7fd2012-11-29 00:36:244140 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044141 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:194142 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504143
[email protected]dc651782009-02-14 01:45:084144 TestDelegate d;
4145 {
[email protected]f7022f32014-08-21 16:32:194146 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364147 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084148
[email protected]f7022f32014-08-21 16:32:194149 r->Start();
4150 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084151
[email protected]255620da2013-08-19 13:14:294152 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084153
[email protected]f7022f32014-08-21 16:32:194154 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:154155 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:194156 EXPECT_TRUE(r->proxy_server().IsEmpty());
4157 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:084158 }
4159}
4160
[email protected]b89290212009-08-14 22:37:354161TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:114162 ASSERT_TRUE(test_server_.Start());
4163
initial.commit586acc5fe2008-07-26 22:42:524164 TestDelegate d;
4165 {
[email protected]f7022f32014-08-21 16:32:194166 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364167 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524168
[email protected]f7022f32014-08-21 16:32:194169 r->Start();
4170 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524171
[email protected]255620da2013-08-19 13:14:294172 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524173
4174 EXPECT_EQ(1, d.response_started_count());
4175 EXPECT_FALSE(d.received_data_before_response());
4176 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:194177 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194178 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:194179 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194180 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164181
[email protected]9e743cd2010-03-16 07:03:534182 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524183 }
initial.commit586acc5fe2008-07-26 22:42:524184}
4185
[email protected]263163f2012-06-14 22:40:344186// This test has the server send a large number of cookies to the client.
4187// To ensure that no number of cookies causes a crash, a galloping binary
4188// search is used to estimate that maximum number of cookies that are accepted
4189// by the browser. Beyond the maximum number, the request will fail with
4190// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304191#if defined(OS_WIN)
4192// http://crbug.com/177916
4193#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4194#else
4195#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4196#endif // defined(OS_WIN)
4197TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:344198 ASSERT_TRUE(test_server_.Start());
4199
4200 int lower_bound = 0;
4201 int upper_bound = 1;
4202
4203 // Double the number of cookies until the response header limits are
4204 // exceeded.
4205 while (DoManyCookiesRequest(upper_bound)) {
4206 lower_bound = upper_bound;
4207 upper_bound *= 2;
4208 ASSERT_LT(upper_bound, 1000000);
4209 }
4210
pkasting6b68a162014-12-01 22:10:294211 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344212 if (tolerance < 2)
4213 tolerance = 2;
4214
4215 // Perform a binary search to find the highest possible number of cookies,
4216 // within the desired tolerance.
4217 while (upper_bound - lower_bound >= tolerance) {
4218 int num_cookies = (lower_bound + upper_bound) / 2;
4219
4220 if (DoManyCookiesRequest(num_cookies))
4221 lower_bound = num_cookies;
4222 else
4223 upper_bound = num_cookies;
4224 }
4225 // Success: the test did not crash.
4226}
4227
[email protected]b89290212009-08-14 22:37:354228TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:114229 ASSERT_TRUE(test_server_.Start());
4230
initial.commit586acc5fe2008-07-26 22:42:524231 TestDelegate d;
4232 {
[email protected]f7022f32014-08-21 16:32:194233 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364234 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524235
[email protected]f7022f32014-08-21 16:32:194236 r->Start();
4237 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524238
[email protected]255620da2013-08-19 13:14:294239 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524240
4241 EXPECT_EQ(1, d.response_started_count());
4242 EXPECT_FALSE(d.received_data_before_response());
4243 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:194244 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194245 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:194246 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194247 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524248 }
[email protected]5d7b373e2009-09-02 07:19:034249}
4250
[email protected]79e1fd62013-06-20 06:50:044251TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
4252 ASSERT_TRUE(test_server_.Start());
4253
4254 TestDelegate d;
4255 {
4256 GURL test_url(test_server_.GetURL(std::string()));
davidben151423e2015-03-23 18:48:364257 scoped_ptr<URLRequest> r(
4258 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044259
4260 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194261 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044262
[email protected]f7022f32014-08-21 16:32:194263 r->Start();
4264 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044265
[email protected]255620da2013-08-19 13:14:294266 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044267
4268 EXPECT_EQ(1, d.response_started_count());
4269 EXPECT_FALSE(d.received_data_before_response());
4270 EXPECT_NE(0, d.bytes_received());
4271 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194272 r->GetSocketAddress().host());
[email protected]79e1fd62013-06-20 06:50:044273 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194274 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044275
4276 EXPECT_TRUE(d.have_full_request_headers());
4277 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4278 }
4279}
4280
[email protected]58e32bb2013-01-21 18:23:254281TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
4282 ASSERT_TRUE(test_server_.Start());
4283
4284 TestDelegate d;
4285 {
[email protected]f7022f32014-08-21 16:32:194286 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364287 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254288
[email protected]f7022f32014-08-21 16:32:194289 r->Start();
4290 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254291
[email protected]255620da2013-08-19 13:14:294292 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254293
4294 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194295 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254296 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4297
4298 EXPECT_EQ(1, d.response_started_count());
4299 EXPECT_FALSE(d.received_data_before_response());
4300 EXPECT_NE(0, d.bytes_received());
4301 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194302 r->GetSocketAddress().host());
[email protected]58e32bb2013-01-21 18:23:254303 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194304 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254305 }
4306}
4307
[email protected]aad63572011-05-24 20:14:394308TEST_F(URLRequestTestHTTP, GetZippedTest) {
4309 ASSERT_TRUE(test_server_.Start());
4310
4311 // Parameter that specifies the Content-Length field in the response:
4312 // C - Compressed length.
4313 // U - Uncompressed length.
4314 // L - Large length (larger than both C & U).
4315 // M - Medium length (between C & U).
4316 // S - Small length (smaller than both C & U).
4317 const char test_parameters[] = "CULMS";
4318 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4319 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444320 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394321 // S has too little data, but we seem to accept it.
4322 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374323 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394324
4325 for (int i = 0; i < num_tests ; i++) {
4326 TestDelegate d;
4327 {
4328 std::string test_file =
4329 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
4330 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394331
[email protected]ceefd7fd2012-11-29 00:36:244332 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094333 TestURLRequestContext context(true);
4334 context.set_network_delegate(&network_delegate);
4335 context.Init();
[email protected]87a09a92011-07-14 15:50:504336
[email protected]f7022f32014-08-21 16:32:194337 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364338 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194339 r->Start();
4340 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394341
[email protected]255620da2013-08-19 13:14:294342 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394343
4344 EXPECT_EQ(1, d.response_started_count());
4345 EXPECT_FALSE(d.received_data_before_response());
4346 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194347 << " status = " << r->status().status()
4348 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394349 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194350 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394351 << " Parameter = \"" << test_file << "\"";
4352 } else {
[email protected]f7022f32014-08-21 16:32:194353 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4354 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394355 << " Parameter = \"" << test_file << "\"";
4356 }
4357 }
4358 }
4359}
4360
tbansala1caf9612015-06-01 20:24:184361TEST_F(URLRequestTestHTTP, NetworkQualityEstimator) {
tbansalea2fb8c2015-05-22 22:23:004362 ASSERT_TRUE(test_server_.Start());
4363 // Enable requests to local host to be used for network quality estimation.
tbansalb177b5392015-06-25 11:13:024364 std::map<std::string, std::string> variation_params;
tbansal1c92d5b2015-08-14 20:14:434365 NetworkQualityEstimator estimator(scoped_ptr<net::ExternalEstimateProvider>(),
4366 variation_params, true, true);
tbansalea2fb8c2015-05-22 22:23:004367
4368 TestDelegate d;
4369 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4370 TestURLRequestContext context(true);
4371 context.set_network_quality_estimator(&estimator);
4372 context.set_network_delegate(&network_delegate);
4373 context.Init();
4374
tbansalafc2c1cb2015-06-15 23:58:594375 std::string url = "echo.html";
tbansalea2fb8c2015-05-22 22:23:004376
4377 scoped_ptr<URLRequest> r(
4378 context.CreateRequest(test_server_.GetURL(url), DEFAULT_PRIORITY, &d));
tbansalea2fb8c2015-05-22 22:23:004379 r->Start();
4380
4381 base::RunLoop().Run();
4382
tbansal9533b6f2015-08-11 22:06:084383 base::TimeDelta rtt;
4384 int32_t kbps;
4385 EXPECT_TRUE(estimator.GetRTTEstimate(&rtt));
4386 EXPECT_TRUE(estimator.GetDownlinkThroughputKbpsEstimate(&kbps));
4387 EXPECT_GE(rtt, base::TimeDelta());
4388 EXPECT_LT(rtt, base::TimeDelta::Max());
4389 EXPECT_GT(kbps, 0);
tbansalea2fb8c2015-05-22 22:23:004390
4391 // Verify that histograms are not populated. They should populate only when
4392 // there is a change in ConnectionType.
4393 base::HistogramTester histogram_tester;
4394 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 0);
4395 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 0);
4396
4397 NetworkChangeNotifier::NotifyObserversOfConnectionTypeChangeForTests(
4398 NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI);
4399 base::MessageLoop::current()->RunUntilIdle();
4400 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 1);
4401 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 1);
4402}
4403
[email protected]58e32bb2013-01-21 18:23:254404TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
4405 ASSERT_TRUE(test_server_.Start());
4406
[email protected]007b3f82013-04-09 08:46:454407 GURL destination_url = test_server_.GetURL(std::string());
4408 GURL original_url =
4409 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254410 TestDelegate d;
davidben151423e2015-03-23 18:48:364411 scoped_ptr<URLRequest> req(
4412 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194413 req->Start();
[email protected]255620da2013-08-19 13:14:294414 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254415
4416 EXPECT_EQ(1, d.response_started_count());
4417 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194418 EXPECT_EQ(destination_url, req->url());
4419 EXPECT_EQ(original_url, req->original_url());
4420 ASSERT_EQ(2U, req->url_chain().size());
4421 EXPECT_EQ(original_url, req->url_chain()[0]);
4422 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254423
4424 LoadTimingInfo load_timing_info_before_redirect;
4425 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4426 &load_timing_info_before_redirect));
4427 TestLoadTimingNotReused(load_timing_info_before_redirect,
4428 CONNECT_TIMING_HAS_DNS_TIMES);
4429
4430 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194431 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254432 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4433
4434 // Check that a new socket was used on redirect, since the server does not
4435 // supposed keep-alive sockets, and that the times before the redirect are
4436 // before the ones recorded for the second request.
4437 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4438 load_timing_info.socket_log_id);
4439 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4440 load_timing_info.connect_timing.connect_start);
4441}
4442
[email protected]8f1ac082011-04-19 21:14:134443TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
4444 ASSERT_TRUE(test_server_.Start());
4445
[email protected]007b3f82013-04-09 08:46:454446 GURL destination_url = test_server_.GetURL(std::string());
4447 GURL middle_redirect_url =
4448 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:134449 GURL original_url = test_server_.GetURL(
4450 "server-redirect?" + middle_redirect_url.spec());
4451 TestDelegate d;
davidben151423e2015-03-23 18:48:364452 scoped_ptr<URLRequest> req(
4453 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194454 req->Start();
[email protected]255620da2013-08-19 13:14:294455 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134456
4457 EXPECT_EQ(1, d.response_started_count());
4458 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194459 EXPECT_EQ(destination_url, req->url());
4460 EXPECT_EQ(original_url, req->original_url());
4461 ASSERT_EQ(3U, req->url_chain().size());
4462 EXPECT_EQ(original_url, req->url_chain()[0]);
4463 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4464 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134465}
4466
[email protected]abe1c4a2013-10-25 19:28:514467// First and second pieces of information logged by delegates to URLRequests.
4468const char kFirstDelegateInfo[] = "Wonderful delegate";
4469const char kSecondDelegateInfo[] = "Exciting delegate";
4470
4471// Logs delegate information to a URLRequest. The first string is logged
4472// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4473// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4474// another asynchronous call is used to clear the delegate information
4475// before calling a callback. The object then deletes itself.
4476class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4477 public:
4478 typedef base::Callback<void()> Callback;
4479
4480 // Each time delegate information is added to the URLRequest, the resulting
4481 // load state is checked. The expected load state after each request is
4482 // passed in as an argument.
4483 static void Run(URLRequest* url_request,
4484 LoadState expected_first_load_state,
4485 LoadState expected_second_load_state,
4486 LoadState expected_third_load_state,
4487 const Callback& callback) {
4488 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4489 url_request,
4490 expected_first_load_state,
4491 expected_second_load_state,
4492 expected_third_load_state,
4493 callback);
4494 logger->Start();
4495 }
4496
4497 // Checks that the log entries, starting with log_position, contain the
4498 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4499 // recorded. Returns the index of entry after the expected number of
4500 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464501 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514502 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514503 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4504 if (log_position + 3 >= entries.size()) {
4505 ADD_FAILURE() << "Not enough log entries";
4506 return entries.size();
4507 }
4508 std::string delegate_info;
4509 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4510 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4511 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4512 &delegate_info));
4513 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4514
4515 ++log_position;
4516 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4517 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4518
4519 ++log_position;
4520 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4521 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4522 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4523 &delegate_info));
4524 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4525
4526 ++log_position;
4527 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4528 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4529
4530 return log_position + 1;
4531 }
4532
[email protected]1826a402014-01-08 15:40:484533 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4534 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464535 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4536 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484537 log_position =
4538 ExpectLogContainsSomewhereAfter(entries,
4539 log_position,
4540 NetLog::TYPE_URL_REQUEST_DELEGATE,
4541 NetLog::PHASE_BEGIN);
4542 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4543 entries[log_position + 1].type);
4544 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4545 return log_position + 1;
4546 }
4547
[email protected]abe1c4a2013-10-25 19:28:514548 private:
4549 friend class base::RefCounted<AsyncDelegateLogger>;
4550
4551 AsyncDelegateLogger(URLRequest* url_request,
4552 LoadState expected_first_load_state,
4553 LoadState expected_second_load_state,
4554 LoadState expected_third_load_state,
4555 const Callback& callback)
4556 : url_request_(url_request),
4557 expected_first_load_state_(expected_first_load_state),
4558 expected_second_load_state_(expected_second_load_state),
4559 expected_third_load_state_(expected_third_load_state),
4560 callback_(callback) {
4561 }
4562
4563 ~AsyncDelegateLogger() {}
4564
4565 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534566 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514567 LoadStateWithParam load_state = url_request_->GetLoadState();
4568 EXPECT_EQ(expected_first_load_state_, load_state.state);
4569 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454570 base::ThreadTaskRunnerHandle::Get()->PostTask(
4571 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514572 }
4573
4574 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534575 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514576 LoadStateWithParam load_state = url_request_->GetLoadState();
4577 EXPECT_EQ(expected_second_load_state_, load_state.state);
4578 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4579 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4580 } else {
4581 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4582 }
skyostil4891b25b2015-06-11 11:43:454583 base::ThreadTaskRunnerHandle::Get()->PostTask(
4584 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514585 }
4586
4587 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534588 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514589 LoadStateWithParam load_state = url_request_->GetLoadState();
4590 EXPECT_EQ(expected_third_load_state_, load_state.state);
4591 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084592 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514593 callback_.Run();
4594 }
4595
4596 URLRequest* url_request_;
4597 const int expected_first_load_state_;
4598 const int expected_second_load_state_;
4599 const int expected_third_load_state_;
4600 const Callback callback_;
4601
4602 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4603};
4604
4605// NetworkDelegate that logs delegate information before a request is started,
4606// before headers are sent, when headers are read, and when auth information
4607// is requested. Uses AsyncDelegateLogger.
4608class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4609 public:
4610 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204611 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514612
4613 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204614 int OnBeforeURLRequest(URLRequest* request,
4615 const CompletionCallback& callback,
4616 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514617 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4618 return RunCallbackAsynchronously(request, callback);
4619 }
4620
dchengb03027d2014-10-21 12:00:204621 int OnBeforeSendHeaders(URLRequest* request,
4622 const CompletionCallback& callback,
4623 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514624 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4625 return RunCallbackAsynchronously(request, callback);
4626 }
4627
dchengb03027d2014-10-21 12:00:204628 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514629 URLRequest* request,
4630 const CompletionCallback& callback,
4631 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164632 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134633 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164634 TestNetworkDelegate::OnHeadersReceived(request,
4635 callback,
[email protected]abe1c4a2013-10-25 19:28:514636 original_response_headers,
[email protected]5f714132014-03-26 10:41:164637 override_response_headers,
4638 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514639 return RunCallbackAsynchronously(request, callback);
4640 }
4641
dchengb03027d2014-10-21 12:00:204642 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514643 URLRequest* request,
4644 const AuthChallengeInfo& auth_info,
4645 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134646 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514647 AsyncDelegateLogger::Run(
4648 request,
4649 LOAD_STATE_WAITING_FOR_DELEGATE,
4650 LOAD_STATE_WAITING_FOR_DELEGATE,
4651 LOAD_STATE_WAITING_FOR_DELEGATE,
4652 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4653 callback, credentials));
4654 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4655 }
4656
4657 private:
4658 static int RunCallbackAsynchronously(
4659 URLRequest* request,
4660 const CompletionCallback& callback) {
4661 AsyncDelegateLogger::Run(
4662 request,
4663 LOAD_STATE_WAITING_FOR_DELEGATE,
4664 LOAD_STATE_WAITING_FOR_DELEGATE,
4665 LOAD_STATE_WAITING_FOR_DELEGATE,
4666 base::Bind(callback, OK));
4667 return ERR_IO_PENDING;
4668 }
4669
4670 static void SetAuthAndResume(const AuthCallback& callback,
4671 AuthCredentials* credentials) {
4672 *credentials = AuthCredentials(kUser, kSecret);
4673 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4674 }
4675
4676 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4677};
4678
4679// URLRequest::Delegate that logs delegate information when the headers
4680// are received, when each read completes, and during redirects. Uses
4681// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4682//
4683// Inherits from TestDelegate to reuse the TestDelegate code to handle
4684// advancing to the next step in most cases, as well as cancellation.
4685class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4686 public:
4687 enum CancelStage {
4688 NO_CANCEL = 0,
4689 CANCEL_ON_RECEIVED_REDIRECT,
4690 CANCEL_ON_RESPONSE_STARTED,
4691 CANCEL_ON_READ_COMPLETED
4692 };
4693
4694 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4695 : cancel_stage_(cancel_stage) {
4696 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4697 set_cancel_in_received_redirect(true);
4698 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4699 set_cancel_in_response_started(true);
4700 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4701 set_cancel_in_received_data(true);
4702 }
dchengb03027d2014-10-21 12:00:204703 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514704
4705 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204706 void OnReceivedRedirect(URLRequest* request,
4707 const RedirectInfo& redirect_info,
4708 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514709 *defer_redirect = true;
4710 AsyncDelegateLogger::Run(
4711 request,
4712 LOAD_STATE_WAITING_FOR_DELEGATE,
4713 LOAD_STATE_WAITING_FOR_DELEGATE,
4714 LOAD_STATE_WAITING_FOR_DELEGATE,
4715 base::Bind(
4716 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594717 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514718 }
4719
dchengb03027d2014-10-21 12:00:204720 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514721 AsyncDelegateLogger::Run(
4722 request,
4723 LOAD_STATE_WAITING_FOR_DELEGATE,
4724 LOAD_STATE_WAITING_FOR_DELEGATE,
4725 LOAD_STATE_WAITING_FOR_DELEGATE,
4726 base::Bind(
4727 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4728 base::Unretained(this), request));
4729 }
4730
dchengb03027d2014-10-21 12:00:204731 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514732 AsyncDelegateLogger::Run(
4733 request,
4734 LOAD_STATE_IDLE,
4735 LOAD_STATE_IDLE,
4736 LOAD_STATE_IDLE,
4737 base::Bind(
4738 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4739 base::Unretained(this), request, bytes_read));
4740 }
4741
4742 private:
4743 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594744 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514745 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594746 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514747 // FollowDeferredRedirect should not be called after cancellation.
4748 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4749 return;
4750 if (!defer_redirect)
4751 request->FollowDeferredRedirect();
4752 }
4753
4754 void OnResponseStartedLoggingComplete(URLRequest* request) {
4755 // The parent class continues the request.
4756 TestDelegate::OnResponseStarted(request);
4757 }
4758
4759 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4760 // The parent class continues the request.
4761 TestDelegate::OnReadCompleted(request, bytes_read);
4762 }
4763
4764 const CancelStage cancel_stage_;
4765
4766 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4767};
4768
4769// Tests handling of delegate info before a request starts.
4770TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4771 ASSERT_TRUE(test_server_.Start());
4772
4773 TestDelegate request_delegate;
4774 TestURLRequestContext context(true);
4775 context.set_network_delegate(NULL);
4776 context.set_net_log(&net_log_);
4777 context.Init();
4778
4779 {
davidben151423e2015-03-23 18:48:364780 scoped_ptr<URLRequest> r(
4781 context.CreateRequest(test_server_.GetURL("empty.html"),
4782 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194783 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514784 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084785 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514786
4787 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194788 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514789 LOAD_STATE_WAITING_FOR_DELEGATE,
4790 LOAD_STATE_WAITING_FOR_DELEGATE,
4791 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194792 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514793
4794 base::RunLoop().Run();
4795
[email protected]f7022f32014-08-21 16:32:194796 EXPECT_EQ(200, r->GetResponseCode());
4797 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514798 }
4799
mmenke43758e62015-05-04 21:09:464800 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514801 net_log_.GetEntries(&entries);
4802 size_t log_position = ExpectLogContainsSomewhereAfter(
4803 entries,
4804 0,
4805 NetLog::TYPE_DELEGATE_INFO,
4806 NetLog::PHASE_BEGIN);
4807
4808 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4809
4810 // Nothing else should add any delegate info to the request.
4811 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4812 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4813}
4814
4815// Tests handling of delegate info from a network delegate.
4816TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4817 ASSERT_TRUE(test_server_.Start());
4818
4819 TestDelegate request_delegate;
4820 AsyncLoggingNetworkDelegate network_delegate;
4821 TestURLRequestContext context(true);
4822 context.set_network_delegate(&network_delegate);
4823 context.set_net_log(&net_log_);
4824 context.Init();
4825
4826 {
davidben151423e2015-03-23 18:48:364827 scoped_ptr<URLRequest> r(
4828 context.CreateRequest(test_server_.GetURL("simple.html"),
4829 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194830 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514831 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084832 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514833
[email protected]f7022f32014-08-21 16:32:194834 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514835 base::RunLoop().Run();
4836
[email protected]f7022f32014-08-21 16:32:194837 EXPECT_EQ(200, r->GetResponseCode());
4838 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514839 EXPECT_EQ(1, network_delegate.created_requests());
4840 EXPECT_EQ(0, network_delegate.destroyed_requests());
4841 }
4842 EXPECT_EQ(1, network_delegate.destroyed_requests());
4843
4844 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464845 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514846 net_log_.GetEntries(&entries);
4847 for (size_t i = 0; i < 3; ++i) {
4848 log_position = ExpectLogContainsSomewhereAfter(
4849 entries,
4850 log_position + 1,
4851 NetLog::TYPE_URL_REQUEST_DELEGATE,
4852 NetLog::PHASE_BEGIN);
4853
4854 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4855 log_position + 1);
4856
4857 ASSERT_LT(log_position, entries.size());
4858 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4859 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484860
4861 if (i == 1) {
4862 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4863 entries, log_position + 1);
4864 }
[email protected]abe1c4a2013-10-25 19:28:514865 }
4866
4867 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4868 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4869}
4870
4871// Tests handling of delegate info from a network delegate in the case of an
4872// HTTP redirect.
4873TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4874 ASSERT_TRUE(test_server_.Start());
4875
4876 TestDelegate request_delegate;
4877 AsyncLoggingNetworkDelegate network_delegate;
4878 TestURLRequestContext context(true);
4879 context.set_network_delegate(&network_delegate);
4880 context.set_net_log(&net_log_);
4881 context.Init();
4882
4883 {
[email protected]f7022f32014-08-21 16:32:194884 scoped_ptr<URLRequest> r(context.CreateRequest(
4885 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364886 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194887 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514888 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084889 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514890
[email protected]f7022f32014-08-21 16:32:194891 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514892 base::RunLoop().Run();
4893
[email protected]f7022f32014-08-21 16:32:194894 EXPECT_EQ(200, r->GetResponseCode());
4895 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514896 EXPECT_EQ(2, network_delegate.created_requests());
4897 EXPECT_EQ(0, network_delegate.destroyed_requests());
4898 }
4899 EXPECT_EQ(1, network_delegate.destroyed_requests());
4900
4901 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464902 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514903 net_log_.GetEntries(&entries);
4904 // The NetworkDelegate logged information in OnBeforeURLRequest,
4905 // OnBeforeSendHeaders, and OnHeadersReceived.
4906 for (size_t i = 0; i < 3; ++i) {
4907 log_position = ExpectLogContainsSomewhereAfter(
4908 entries,
4909 log_position + 1,
4910 NetLog::TYPE_URL_REQUEST_DELEGATE,
4911 NetLog::PHASE_BEGIN);
4912
4913 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4914 log_position + 1);
4915
4916 ASSERT_LT(log_position, entries.size());
4917 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4918 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484919
4920 if (i == 1) {
4921 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4922 entries, log_position + 1);
4923 }
[email protected]abe1c4a2013-10-25 19:28:514924 }
4925
4926 // The URLRequest::Delegate then gets informed about the redirect.
4927 log_position = ExpectLogContainsSomewhereAfter(
4928 entries,
4929 log_position + 1,
4930 NetLog::TYPE_URL_REQUEST_DELEGATE,
4931 NetLog::PHASE_BEGIN);
4932
4933 // The NetworkDelegate logged information in the same three events as before.
4934 for (size_t i = 0; i < 3; ++i) {
4935 log_position = ExpectLogContainsSomewhereAfter(
4936 entries,
4937 log_position + 1,
4938 NetLog::TYPE_URL_REQUEST_DELEGATE,
4939 NetLog::PHASE_BEGIN);
4940
4941 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4942 log_position + 1);
4943
4944 ASSERT_LT(log_position, entries.size());
4945 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4946 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4947 }
4948
4949 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4950 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4951}
4952
4953// Tests handling of delegate info from a network delegate in the case of HTTP
4954// AUTH.
4955TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4956 ASSERT_TRUE(test_server_.Start());
4957
4958 TestDelegate request_delegate;
4959 AsyncLoggingNetworkDelegate network_delegate;
4960 TestURLRequestContext context(true);
4961 context.set_network_delegate(&network_delegate);
4962 context.set_net_log(&net_log_);
4963 context.Init();
4964
4965 {
davidben151423e2015-03-23 18:48:364966 scoped_ptr<URLRequest> r(
4967 context.CreateRequest(test_server_.GetURL("auth-basic"),
4968 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194969 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514970 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084971 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514972
[email protected]f7022f32014-08-21 16:32:194973 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514974 base::RunLoop().Run();
4975
[email protected]f7022f32014-08-21 16:32:194976 EXPECT_EQ(200, r->GetResponseCode());
4977 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514978 EXPECT_EQ(1, network_delegate.created_requests());
4979 EXPECT_EQ(0, network_delegate.destroyed_requests());
4980 }
4981 EXPECT_EQ(1, network_delegate.destroyed_requests());
4982
4983 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464984 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514985 net_log_.GetEntries(&entries);
4986 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4987 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4988 // OnBeforeURLRequest and OnBeforeSendHeaders.
4989 for (size_t i = 0; i < 6; ++i) {
4990 log_position = ExpectLogContainsSomewhereAfter(
4991 entries,
4992 log_position + 1,
4993 NetLog::TYPE_URL_REQUEST_DELEGATE,
4994 NetLog::PHASE_BEGIN);
4995
4996 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4997 log_position + 1);
4998
4999 ASSERT_LT(log_position, entries.size());
5000 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5001 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485002
5003 if (i == 1) {
5004 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5005 entries, log_position + 1);
5006 }
[email protected]abe1c4a2013-10-25 19:28:515007 }
5008
5009 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5010 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5011}
5012
5013// Tests handling of delegate info from a URLRequest::Delegate.
5014TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
5015 ASSERT_TRUE(test_server_.Start());
5016
5017 AsyncLoggingUrlRequestDelegate request_delegate(
5018 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5019 TestURLRequestContext context(true);
5020 context.set_network_delegate(NULL);
5021 context.set_net_log(&net_log_);
5022 context.Init();
5023
5024 {
5025 // A chunked response with delays between chunks is used to make sure that
5026 // attempts by the URLRequest delegate to log information while reading the
5027 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485028 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515029 // that it occurs.
[email protected]f7022f32014-08-21 16:32:195030 scoped_ptr<URLRequest> r(context.CreateRequest(
5031 test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365032 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195033 LoadStateWithParam load_state = r->GetLoadState();
5034 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515035 base::RunLoop().Run();
5036
[email protected]f7022f32014-08-21 16:32:195037 EXPECT_EQ(200, r->GetResponseCode());
5038 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515039 }
5040
mmenke43758e62015-05-04 21:09:465041 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515042 net_log_.GetEntries(&entries);
5043
[email protected]1826a402014-01-08 15:40:485044 size_t log_position = 0;
5045
5046 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5047 entries, log_position);
5048
[email protected]abe1c4a2013-10-25 19:28:515049 // The delegate info should only have been logged on header complete. Other
5050 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:485051 log_position =
5052 ExpectLogContainsSomewhereAfter(entries,
5053 log_position + 1,
5054 NetLog::TYPE_URL_REQUEST_DELEGATE,
5055 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515056
5057 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5058 log_position + 1);
5059
5060 ASSERT_LT(log_position, entries.size());
5061 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5062 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5063
5064 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5065 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5066 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5067 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5068}
5069
5070// Tests handling of delegate info from a URLRequest::Delegate in the case of
5071// an HTTP redirect.
5072TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
5073 ASSERT_TRUE(test_server_.Start());
5074
5075 AsyncLoggingUrlRequestDelegate request_delegate(
5076 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5077 TestURLRequestContext context(true);
5078 context.set_network_delegate(NULL);
5079 context.set_net_log(&net_log_);
5080 context.Init();
5081
5082 {
[email protected]f7022f32014-08-21 16:32:195083 scoped_ptr<URLRequest> r(context.CreateRequest(
5084 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365085 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195086 LoadStateWithParam load_state = r->GetLoadState();
5087 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515088 base::RunLoop().Run();
5089
[email protected]f7022f32014-08-21 16:32:195090 EXPECT_EQ(200, r->GetResponseCode());
5091 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515092 }
5093
mmenke43758e62015-05-04 21:09:465094 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515095 net_log_.GetEntries(&entries);
5096
5097 // Delegate info should only have been logged in OnReceivedRedirect and
5098 // OnResponseStarted.
5099 size_t log_position = 0;
5100 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485101 if (i == 0) {
5102 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5103 entries, log_position) + 1;
5104 }
5105
[email protected]abe1c4a2013-10-25 19:28:515106 log_position = ExpectLogContainsSomewhereAfter(
5107 entries,
5108 log_position,
5109 NetLog::TYPE_URL_REQUEST_DELEGATE,
5110 NetLog::PHASE_BEGIN);
5111
5112 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5113 log_position + 1);
5114
5115 ASSERT_LT(log_position, entries.size());
5116 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5117 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5118 }
5119
5120 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5121 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5122 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5123 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5124}
5125
5126// Tests handling of delegate info from a URLRequest::Delegate in the case of
5127// an HTTP redirect, with cancellation at various points.
5128TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
5129 ASSERT_TRUE(test_server_.Start());
5130
5131 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5132 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5133 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5134 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5135 };
5136
5137 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5138 ++test_case) {
5139 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5140 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:515141 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:515142 context.set_network_delegate(NULL);
5143 context.set_net_log(&net_log);
5144 context.Init();
5145
5146 {
[email protected]f7022f32014-08-21 16:32:195147 scoped_ptr<URLRequest> r(context.CreateRequest(
5148 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365149 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195150 LoadStateWithParam load_state = r->GetLoadState();
5151 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515152 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195153 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515154 }
5155
mmenke43758e62015-05-04 21:09:465156 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515157 net_log.GetEntries(&entries);
5158
5159 // Delegate info is always logged in both OnReceivedRedirect and
5160 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5161 // OnResponseStarted delegate call is after cancellation, but logging is
5162 // still currently supported in that call.
5163 size_t log_position = 0;
5164 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485165 if (i == 0) {
5166 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5167 entries, log_position) + 1;
5168 }
5169
[email protected]abe1c4a2013-10-25 19:28:515170 log_position = ExpectLogContainsSomewhereAfter(
5171 entries,
5172 log_position,
5173 NetLog::TYPE_URL_REQUEST_DELEGATE,
5174 NetLog::PHASE_BEGIN);
5175
5176 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5177 log_position + 1);
5178
5179 ASSERT_LT(log_position, entries.size());
5180 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5181 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5182 }
5183
5184 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5185 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5186 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5187 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5188 }
5189}
5190
[email protected]847c0fa92012-11-06 16:37:425191namespace {
5192
5193const char kExtraHeader[] = "Allow-Snafu";
5194const char kExtraValue[] = "fubar";
5195
5196class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205197 void OnReceivedRedirect(URLRequest* request,
5198 const RedirectInfo& redirect_info,
5199 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595200 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425201 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5202 }
5203};
5204
5205} // namespace
5206
5207TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
5208 ASSERT_TRUE(test_server_.Start());
5209
5210 GURL destination_url = test_server_.GetURL(
5211 "echoheader?" + std::string(kExtraHeader));
5212 GURL original_url = test_server_.GetURL(
5213 "server-redirect?" + destination_url.spec());
5214 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:365215 scoped_ptr<URLRequest> req(
5216 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195217 req->Start();
[email protected]255620da2013-08-19 13:14:295218 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425219
5220 std::string value;
[email protected]f7022f32014-08-21 16:32:195221 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425222 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5223 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195224 EXPECT_FALSE(req->is_pending());
5225 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425226 EXPECT_EQ(kExtraValue, d.data_received());
5227}
5228
[email protected]251a1b92012-11-13 11:01:095229namespace {
5230
5231const char kExtraHeaderToRemove[] = "To-Be-Removed";
5232
5233class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205234 void OnReceivedRedirect(URLRequest* request,
5235 const RedirectInfo& redirect_info,
5236 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595237 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095238 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5239 }
5240};
5241
5242} // namespace
5243
5244TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
5245 ASSERT_TRUE(test_server_.Start());
5246
5247 GURL destination_url = test_server_.GetURL(
5248 "echoheader?" + std::string(kExtraHeaderToRemove));
5249 GURL original_url = test_server_.GetURL(
5250 "server-redirect?" + destination_url.spec());
5251 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:365252 scoped_ptr<URLRequest> req(
5253 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195254 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5255 req->Start();
[email protected]255620da2013-08-19 13:14:295256 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095257
5258 std::string value;
[email protected]f7022f32014-08-21 16:32:195259 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095260 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195261 EXPECT_FALSE(req->is_pending());
5262 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095263 EXPECT_EQ("None", d.data_received());
5264}
5265
[email protected]316c1e5e2012-09-12 15:17:445266TEST_F(URLRequestTestHTTP, CancelTest) {
5267 TestDelegate d;
5268 {
[email protected]f7022f32014-08-21 16:32:195269 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365270 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445271
[email protected]f7022f32014-08-21 16:32:195272 r->Start();
5273 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445274
[email protected]f7022f32014-08-21 16:32:195275 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445276
[email protected]255620da2013-08-19 13:14:295277 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445278
5279 // We expect to receive OnResponseStarted even though the request has been
5280 // cancelled.
5281 EXPECT_EQ(1, d.response_started_count());
5282 EXPECT_EQ(0, d.bytes_received());
5283 EXPECT_FALSE(d.received_data_before_response());
5284 }
5285}
5286
5287TEST_F(URLRequestTestHTTP, CancelTest2) {
5288 ASSERT_TRUE(test_server_.Start());
5289
5290 TestDelegate d;
5291 {
[email protected]f7022f32014-08-21 16:32:195292 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365293 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445294
5295 d.set_cancel_in_response_started(true);
5296
[email protected]f7022f32014-08-21 16:32:195297 r->Start();
5298 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445299
[email protected]255620da2013-08-19 13:14:295300 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445301
5302 EXPECT_EQ(1, d.response_started_count());
5303 EXPECT_EQ(0, d.bytes_received());
5304 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195305 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445306 }
5307}
5308
5309TEST_F(URLRequestTestHTTP, CancelTest3) {
5310 ASSERT_TRUE(test_server_.Start());
5311
5312 TestDelegate d;
5313 {
[email protected]f7022f32014-08-21 16:32:195314 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365315 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445316
5317 d.set_cancel_in_received_data(true);
5318
[email protected]f7022f32014-08-21 16:32:195319 r->Start();
5320 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445321
[email protected]255620da2013-08-19 13:14:295322 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445323
5324 EXPECT_EQ(1, d.response_started_count());
5325 // There is no guarantee about how much data was received
5326 // before the cancel was issued. It could have been 0 bytes,
5327 // or it could have been all the bytes.
5328 // EXPECT_EQ(0, d.bytes_received());
5329 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195330 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445331 }
5332}
5333
5334TEST_F(URLRequestTestHTTP, CancelTest4) {
5335 ASSERT_TRUE(test_server_.Start());
5336
5337 TestDelegate d;
5338 {
[email protected]f7022f32014-08-21 16:32:195339 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365340 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445341
[email protected]f7022f32014-08-21 16:32:195342 r->Start();
5343 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445344
5345 // The request will be implicitly canceled when it is destroyed. The
5346 // test delegate must not post a quit message when this happens because
5347 // this test doesn't actually have a message loop. The quit message would
5348 // get put on this thread's message queue and the next test would exit
5349 // early, causing problems.
5350 d.set_quit_on_complete(false);
5351 }
5352 // expect things to just cleanup properly.
5353
5354 // we won't actually get a received reponse here because we've never run the
5355 // message loop
5356 EXPECT_FALSE(d.received_data_before_response());
5357 EXPECT_EQ(0, d.bytes_received());
5358}
5359
5360TEST_F(URLRequestTestHTTP, CancelTest5) {
5361 ASSERT_TRUE(test_server_.Start());
5362
5363 // populate cache
5364 {
5365 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195366 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365367 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195368 r->Start();
[email protected]255620da2013-08-19 13:14:295369 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195370 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445371 }
5372
5373 // cancel read from cache (see bug 990242)
5374 {
5375 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195376 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365377 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195378 r->Start();
5379 r->Cancel();
[email protected]255620da2013-08-19 13:14:295380 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445381
[email protected]f7022f32014-08-21 16:32:195382 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445383 EXPECT_EQ(1, d.response_started_count());
5384 EXPECT_EQ(0, d.bytes_received());
5385 EXPECT_FALSE(d.received_data_before_response());
5386 }
5387}
5388
5389TEST_F(URLRequestTestHTTP, PostTest) {
5390 ASSERT_TRUE(test_server_.Start());
5391 HTTPUploadDataOperationTest("POST");
5392}
5393
5394TEST_F(URLRequestTestHTTP, PutTest) {
5395 ASSERT_TRUE(test_server_.Start());
5396 HTTPUploadDataOperationTest("PUT");
5397}
5398
5399TEST_F(URLRequestTestHTTP, PostEmptyTest) {
5400 ASSERT_TRUE(test_server_.Start());
5401
5402 TestDelegate d;
5403 {
[email protected]f7022f32014-08-21 16:32:195404 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365405 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195406 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445407
[email protected]f7022f32014-08-21 16:32:195408 r->Start();
5409 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445410
[email protected]255620da2013-08-19 13:14:295411 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445412
[email protected]329b68b2012-11-14 17:54:275413 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195414 << "request failed: " << r->status().status()
5415 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445416
5417 EXPECT_FALSE(d.received_data_before_response());
5418 EXPECT_TRUE(d.data_received().empty());
5419 }
5420}
5421
5422TEST_F(URLRequestTestHTTP, PostFileTest) {
5423 ASSERT_TRUE(test_server_.Start());
5424
5425 TestDelegate d;
5426 {
[email protected]f7022f32014-08-21 16:32:195427 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365428 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195429 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445430
[email protected]6cdfd7f2013-02-08 20:40:155431 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445432 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025433 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445434
[email protected]f288ef02012-12-15 20:28:285435 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445436
[email protected]6cdfd7f2013-02-08 20:40:155437 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445438 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475439 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445440 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:365441 element_readers.push_back(
skyostil4891b25b2015-06-11 11:43:455442 new UploadFileElementReader(base::ThreadTaskRunnerHandle::Get().get(),
5443 path, 0, kuint64max, base::Time()));
mmenkecbc2b712014-10-09 20:29:075444 r->set_upload(make_scoped_ptr<UploadDataStream>(
5445 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:445446
[email protected]f7022f32014-08-21 16:32:195447 r->Start();
5448 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445449
[email protected]255620da2013-08-19 13:14:295450 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445451
pkasting6b68a162014-12-01 22:10:295452 int64 size64 = 0;
5453 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5454 ASSERT_LE(size64, std::numeric_limits<int>::max());
5455 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175456 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445457
[email protected]7600d0b2013-12-08 21:43:305458 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445459
[email protected]329b68b2012-11-14 17:54:275460 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195461 << "request failed: " << r->status().status()
5462 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445463
5464 EXPECT_FALSE(d.received_data_before_response());
5465
[email protected]329b68b2012-11-14 17:54:275466 EXPECT_EQ(size, d.bytes_received());
5467 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445468 }
5469}
5470
[email protected]999dd8c2013-11-12 06:45:545471TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
5472 ASSERT_TRUE(test_server_.Start());
5473
5474 TestDelegate d;
5475 {
[email protected]f7022f32014-08-21 16:32:195476 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365477 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195478 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545479
5480 ScopedVector<UploadElementReader> element_readers;
5481
5482 element_readers.push_back(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455483 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545484 base::FilePath(FILE_PATH_LITERAL(
5485 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
skyostil4891b25b2015-06-11 11:43:455486 0, kuint64max, base::Time()));
mmenkecbc2b712014-10-09 20:29:075487 r->set_upload(make_scoped_ptr<UploadDataStream>(
5488 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]999dd8c2013-11-12 06:45:545489
[email protected]f7022f32014-08-21 16:32:195490 r->Start();
5491 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545492
5493 base::RunLoop().Run();
5494
[email protected]999dd8c2013-11-12 06:45:545495 EXPECT_TRUE(d.request_failed());
5496 EXPECT_FALSE(d.received_data_before_response());
5497 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195498 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5499 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545500 }
5501}
5502
[email protected]316c1e5e2012-09-12 15:17:445503TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5504 ASSERT_TRUE(test_server_.Start());
5505
5506 TestDelegate d;
5507 {
[email protected]f7022f32014-08-21 16:32:195508 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365509 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195510 r->EnableChunkedUpload();
5511 r->set_method("POST");
5512 AddChunksToUpload(r.get());
5513 r->Start();
5514 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445515
[email protected]255620da2013-08-19 13:14:295516 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445517
[email protected]f7022f32014-08-21 16:32:195518 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445519 }
5520}
5521
[email protected]329b68b2012-11-14 17:54:275522TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5523 ASSERT_TRUE(test_server_.Start());
5524
5525 TestDelegate d;
5526 {
[email protected]f7022f32014-08-21 16:32:195527 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365528 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195529 r->EnableChunkedUpload();
5530 r->set_method("POST");
5531 r->Start();
5532 EXPECT_TRUE(r->is_pending());
5533 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295534 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275535
[email protected]f7022f32014-08-21 16:32:195536 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275537 }
5538}
5539
[email protected]316c1e5e2012-09-12 15:17:445540TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5541 ASSERT_TRUE(test_server_.Start());
5542
5543 TestDelegate d;
5544 {
[email protected]f7022f32014-08-21 16:32:195545 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365546 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195547 r->EnableChunkedUpload();
5548 r->set_method("POST");
5549 r->Start();
5550 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445551
[email protected]255620da2013-08-19 13:14:295552 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195553 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295554 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445555
[email protected]f7022f32014-08-21 16:32:195556 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445557 }
5558}
5559
5560TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5561 ASSERT_TRUE(test_server_.Start());
5562
5563 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195564 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365565 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195566 req->Start();
[email protected]255620da2013-08-19 13:14:295567 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445568
[email protected]f7022f32014-08-21 16:32:195569 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445570
5571 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195572 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445573
5574 std::string header;
5575 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5576 EXPECT_EQ("private", header);
5577
5578 header.clear();
5579 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5580 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5581
5582 // The response has two "X-Multiple-Entries" headers.
5583 // This verfies our output has them concatenated together.
5584 header.clear();
5585 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5586 EXPECT_EQ("a, b", header);
5587}
5588
[email protected]242d8562012-10-30 21:20:465589TEST_F(URLRequestTestHTTP, ProcessSTS) {
estarka5da76702015-04-09 04:00:165590 SpawnedTestServer::SSLOptions ssl_options(
5591 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475592 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5593 ssl_options,
5594 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465595 ASSERT_TRUE(https_test_server.Start());
5596
estarka5da76702015-04-09 04:00:165597 std::string test_server_hostname = https_test_server.GetURL("").host();
5598
[email protected]242d8562012-10-30 21:20:465599 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195600 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365601 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5602 &d));
[email protected]f7022f32014-08-21 16:32:195603 request->Start();
[email protected]255620da2013-08-19 13:14:295604 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465605
5606 TransportSecurityState* security_state =
5607 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405608 TransportSecurityState::STSState sts_state;
5609 TransportSecurityState::PKPState pkp_state;
5610 EXPECT_TRUE(
5611 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5612 EXPECT_FALSE(
5613 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5614 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5615 sts_state.upgrade_mode);
5616 EXPECT_TRUE(sts_state.include_subdomains);
5617 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275618#if defined(OS_ANDROID)
5619 // Android's CertVerifyProc does not (yet) handle pins.
5620#else
martijnc0d6b622015-06-30 19:14:405621 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
[email protected]37fd55fb2013-06-29 13:13:275622#endif
5623}
5624
estarka5da76702015-04-09 04:00:165625TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
mmenke9f2ec60c2015-06-01 20:59:475626 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5627 SpawnedTestServer::SSLOptions(),
5628 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165629 ASSERT_TRUE(https_test_server.Start());
5630 // Make sure this test fails if the test server is changed to not
5631 // listen on an IP by default.
5632 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5633 std::string test_server_hostname = https_test_server.GetURL("").host();
5634
5635 TestDelegate d;
5636 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5637 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5638 &d));
5639 request->Start();
5640 base::RunLoop().Run();
5641
5642 TransportSecurityState* security_state =
5643 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405644 TransportSecurityState::STSState sts_state;
5645 EXPECT_FALSE(
5646 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165647}
5648
[email protected]37fd55fb2013-06-29 13:13:275649// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5650// reject HPKP headers, and a test setting only HPKP headers will fail (no
martijnc0d6b622015-06-30 19:14:405651// PKPState present because header rejected).
[email protected]37fd55fb2013-06-29 13:13:275652#if defined(OS_ANDROID)
5653#define MAYBE_ProcessPKP DISABLED_ProcessPKP
estark06e0dac2015-08-07 21:56:015654#define MAYBE_ProcessPKPAndSendReport DISABLED_ProcessPKPAndSendReport
5655#define MAYBE_ProcessPKPReportOnly DISABLED_ProcessPKPReportOnly
5656#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5657 DISABLED_ProcessPKPReportOnlyWithNoViolation
[email protected]37fd55fb2013-06-29 13:13:275658#else
5659#define MAYBE_ProcessPKP ProcessPKP
estark06e0dac2015-08-07 21:56:015660#define MAYBE_ProcessPKPAndSendReport ProcessPKPAndSendReport
5661#define MAYBE_ProcessPKPReportOnly ProcessPKPReportOnly
5662#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5663 ProcessPKPReportOnlyWithNoViolation
[email protected]37fd55fb2013-06-29 13:13:275664#endif
5665
estark06e0dac2015-08-07 21:56:015666namespace {
5667const char kHPKPReportUri[] = "https://hpkp-report.test";
5668} // namespace
5669
[email protected]37fd55fb2013-06-29 13:13:275670// Tests that enabling HPKP on a domain does not affect the HSTS
5671// validity/expiration.
5672TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estark06e0dac2015-08-07 21:56:015673 GURL report_uri(kHPKPReportUri);
estarka5da76702015-04-09 04:00:165674 SpawnedTestServer::SSLOptions ssl_options(
5675 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475676 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5677 ssl_options,
5678 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275679 ASSERT_TRUE(https_test_server.Start());
5680
estarka5da76702015-04-09 04:00:165681 std::string test_server_hostname = https_test_server.GetURL("").host();
5682
[email protected]37fd55fb2013-06-29 13:13:275683 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195684 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365685 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5686 &d));
[email protected]f7022f32014-08-21 16:32:195687 request->Start();
[email protected]255620da2013-08-19 13:14:295688 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275689
5690 TransportSecurityState* security_state =
5691 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405692 TransportSecurityState::STSState sts_state;
5693 TransportSecurityState::PKPState pkp_state;
5694 EXPECT_FALSE(
5695 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5696 EXPECT_TRUE(
5697 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5698 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
5699 sts_state.upgrade_mode);
5700 EXPECT_FALSE(sts_state.include_subdomains);
5701 EXPECT_FALSE(pkp_state.include_subdomains);
5702 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:015703 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:405704 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:465705}
5706
estark06e0dac2015-08-07 21:56:015707// Tests that reports get sent on HPKP violations when a report-uri is set.
5708TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPAndSendReport) {
5709 GURL report_uri(kHPKPReportUri);
5710 SpawnedTestServer::SSLOptions ssl_options(
5711 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
5712 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5713 ssl_options,
5714 base::FilePath(kTestFilePath));
5715
5716 ASSERT_TRUE(https_test_server.Start());
5717
5718 std::string test_server_hostname = https_test_server.GetURL("").host();
5719
5720 // Set up a pin for |test_server_hostname|.
5721 TransportSecurityState security_state;
5722 const base::Time current_time(base::Time::Now());
5723 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
5724 HashValueVector hashes;
5725 HashValue hash1;
5726 HashValue hash2;
5727 // The values here don't matter, as long as they are different from
5728 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:445729 ASSERT_TRUE(
5730 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
5731 ASSERT_TRUE(
5732 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:015733 hashes.push_back(hash1);
5734 hashes.push_back(hash2);
5735 security_state.AddHPKP(test_server_hostname, expiry,
5736 false, /* include subdomains */
5737 hashes, report_uri);
5738
5739 MockCertificateReportSender mock_report_sender;
5740 security_state.SetReportSender(&mock_report_sender);
5741
5742 // Set up a MockCertVerifier to trigger a violation of the previously
5743 // set pin.
5744 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5745 ASSERT_TRUE(cert);
5746
5747 MockCertVerifier cert_verifier;
5748 CertVerifyResult verify_result;
5749 verify_result.verified_cert = cert;
5750 verify_result.is_issued_by_known_root = true;
5751 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:445752 ASSERT_TRUE(
5753 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:015754 verify_result.public_key_hashes.push_back(hash3);
5755 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5756
5757 TestNetworkDelegate network_delegate;
5758 TestURLRequestContext context(true);
5759 context.set_transport_security_state(&security_state);
5760 context.set_network_delegate(&network_delegate);
5761 context.set_cert_verifier(&cert_verifier);
5762 context.Init();
5763
5764 // Now send a request to trigger the violation.
5765 TestDelegate d;
5766 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
5767 https_test_server.GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
5768 violating_request->Start();
5769 base::RunLoop().Run();
5770
5771 // Check that a report was sent.
5772 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5773 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5774 scoped_ptr<base::Value> value(
5775 base::JSONReader::Read(mock_report_sender.latest_report()));
5776 ASSERT_TRUE(value);
5777 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
5778 base::DictionaryValue* report_dict;
5779 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
5780 std::string report_hostname;
5781 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
5782 EXPECT_EQ(test_server_hostname, report_hostname);
5783}
5784
5785// Tests that reports get sent on requests with
5786// Public-Key-Pins-Report-Only headers.
5787TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnly) {
5788 GURL report_uri(kHPKPReportUri);
5789 SpawnedTestServer::SSLOptions ssl_options(
5790 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
5791 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5792 ssl_options,
5793 base::FilePath(kTestFilePath));
5794
5795 ASSERT_TRUE(https_test_server.Start());
5796
5797 std::string test_server_hostname = https_test_server.GetURL("").host();
5798
5799 TransportSecurityState security_state;
5800 MockCertificateReportSender mock_report_sender;
5801 security_state.SetReportSender(&mock_report_sender);
5802
5803 // Set up a MockCertVerifier to violate the pin in the Report-Only
5804 // header.
5805 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5806 ASSERT_TRUE(cert);
5807
5808 MockCertVerifier cert_verifier;
5809 CertVerifyResult verify_result;
5810 verify_result.verified_cert = cert;
5811 verify_result.is_issued_by_known_root = true;
5812 HashValue hash;
5813 // This value doesn't matter, as long as it is different from the pins
5814 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:445815 ASSERT_TRUE(
5816 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:015817 verify_result.public_key_hashes.push_back(hash);
5818 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5819
5820 TestNetworkDelegate network_delegate;
5821 TestURLRequestContext context(true);
5822 context.set_transport_security_state(&security_state);
5823 context.set_network_delegate(&network_delegate);
5824 context.set_cert_verifier(&cert_verifier);
5825 context.Init();
5826
5827 // Now send a request to trigger the violation.
5828 TestDelegate d;
5829 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
5830 https_test_server.GetURL("files/hpkp-headers-report-only.html"),
5831 DEFAULT_PRIORITY, &d));
5832 violating_request->Start();
5833 base::RunLoop().Run();
5834
5835 // Check that a report was sent.
5836 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5837 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5838 scoped_ptr<base::Value> value(
5839 base::JSONReader::Read(mock_report_sender.latest_report()));
5840 ASSERT_TRUE(value);
5841 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
5842 base::DictionaryValue* report_dict;
5843 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
5844 std::string report_hostname;
5845 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
5846 EXPECT_EQ(test_server_hostname, report_hostname);
5847}
5848
5849// Tests that reports do not get sent on requests with
5850// Public-Key-Pins-Report-Only headers that don't have pin violations.
5851TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnlyWithNoViolation) {
5852 GURL report_uri(kHPKPReportUri);
5853 SpawnedTestServer::SSLOptions ssl_options(
5854 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
5855 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5856 ssl_options,
5857 base::FilePath(kTestFilePath));
5858
5859 ASSERT_TRUE(https_test_server.Start());
5860
5861 std::string test_server_hostname = https_test_server.GetURL("").host();
5862
5863 TransportSecurityState security_state;
5864 MockCertificateReportSender mock_report_sender;
5865 security_state.SetReportSender(&mock_report_sender);
5866
5867 TestNetworkDelegate network_delegate;
5868 MockCertVerifier mock_cert_verifier;
5869 TestURLRequestContext context(true);
5870 context.set_transport_security_state(&security_state);
5871 context.set_network_delegate(&network_delegate);
5872 context.set_cert_verifier(&mock_cert_verifier);
5873 mock_cert_verifier.set_default_result(OK);
5874 context.Init();
5875
5876 // Now send a request that does not trigger the violation.
5877 TestDelegate d;
5878 scoped_ptr<URLRequest> request(context.CreateRequest(
5879 https_test_server.GetURL("files/hpkp-headers-report-only.html"),
5880 DEFAULT_PRIORITY, &d));
5881 request->Start();
5882 base::RunLoop().Run();
5883
5884 // Check that a report was not sent.
5885 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
5886 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
5887}
5888
estarka5da76702015-04-09 04:00:165889TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
mmenke9f2ec60c2015-06-01 20:59:475890 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5891 SpawnedTestServer::SSLOptions(),
5892 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165893 ASSERT_TRUE(https_test_server.Start());
5894 // Make sure this test fails if the test server is changed to not
5895 // listen on an IP by default.
5896 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5897 std::string test_server_hostname = https_test_server.GetURL("").host();
5898
5899 TestDelegate d;
5900 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5901 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5902 &d));
5903 request->Start();
5904 base::RunLoop().Run();
5905
5906 TransportSecurityState* security_state =
5907 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405908 TransportSecurityState::PKPState pkp_state;
5909 EXPECT_FALSE(
5910 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:165911}
5912
[email protected]242d8562012-10-30 21:20:465913TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
estarka5da76702015-04-09 04:00:165914 SpawnedTestServer::SSLOptions ssl_options(
5915 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475916 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5917 ssl_options,
5918 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465919 ASSERT_TRUE(https_test_server.Start());
5920
estarka5da76702015-04-09 04:00:165921 std::string test_server_hostname = https_test_server.GetURL("").host();
5922
[email protected]242d8562012-10-30 21:20:465923 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195924 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]242d8562012-10-30 21:20:465925 https_test_server.GetURL("files/hsts-multiple-headers.html"),
davidben151423e2015-03-23 18:48:365926 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195927 request->Start();
[email protected]255620da2013-08-19 13:14:295928 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465929
5930 // We should have set parameters from the first header, not the second.
5931 TransportSecurityState* security_state =
5932 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405933 TransportSecurityState::STSState sts_state;
5934 EXPECT_TRUE(
5935 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5936 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5937 sts_state.upgrade_mode);
5938 EXPECT_FALSE(sts_state.include_subdomains);
5939 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:465940}
5941
[email protected]9f972ec2013-04-10 20:24:365942TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
estarka5da76702015-04-09 04:00:165943 SpawnedTestServer::SSLOptions ssl_options(
5944 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475945 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5946 ssl_options,
5947 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:365948 ASSERT_TRUE(https_test_server.Start());
5949
estarka5da76702015-04-09 04:00:165950 std::string test_server_hostname = https_test_server.GetURL("").host();
5951
[email protected]9f972ec2013-04-10 20:24:365952 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195953 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]9f972ec2013-04-10 20:24:365954 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
davidben151423e2015-03-23 18:48:365955 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195956 request->Start();
[email protected]255620da2013-08-19 13:14:295957 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365958
5959 // We should have set parameters from the first header, not the second.
5960 TransportSecurityState* security_state =
5961 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405962 TransportSecurityState::STSState sts_state;
5963 TransportSecurityState::PKPState pkp_state;
5964 EXPECT_TRUE(
5965 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5966 EXPECT_TRUE(
5967 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5968 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5969 sts_state.upgrade_mode);
[email protected]9f972ec2013-04-10 20:24:365970#if defined(OS_ANDROID)
5971 // Android's CertVerifyProc does not (yet) handle pins.
5972#else
martijnc0d6b622015-06-30 19:14:405973 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
[email protected]9f972ec2013-04-10 20:24:365974#endif
martijnc0d6b622015-06-30 19:14:405975 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:365976
[email protected]a165f092013-06-12 16:10:055977 // Even though there is an HSTS header asserting includeSubdomains, it is
5978 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:405979 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:055980 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:405981 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365982}
5983
[email protected]37fd55fb2013-06-29 13:13:275984// Tests that when multiple HPKP headers are present, asserting different
5985// policies, that only the first such policy is processed.
5986TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
estarka5da76702015-04-09 04:00:165987 SpawnedTestServer::SSLOptions ssl_options(
5988 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475989 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5990 ssl_options,
5991 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275992 ASSERT_TRUE(https_test_server.Start());
5993
estarka5da76702015-04-09 04:00:165994 std::string test_server_hostname = https_test_server.GetURL("").host();
5995
[email protected]37fd55fb2013-06-29 13:13:275996 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195997 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]37fd55fb2013-06-29 13:13:275998 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:365999 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196000 request->Start();
[email protected]255620da2013-08-19 13:14:296001 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276002
6003 TransportSecurityState* security_state =
6004 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406005 TransportSecurityState::STSState sts_state;
6006 TransportSecurityState::PKPState pkp_state;
6007 EXPECT_TRUE(
6008 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6009 EXPECT_TRUE(
6010 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6011 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6012 sts_state.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:276013#if defined(OS_ANDROID)
6014 // Android's CertVerifyProc does not (yet) handle pins.
6015#else
martijnc0d6b622015-06-30 19:14:406016 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
[email protected]37fd55fb2013-06-29 13:13:276017#endif
martijnc0d6b622015-06-30 19:14:406018 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276019
martijnc0d6b622015-06-30 19:14:406020 EXPECT_TRUE(sts_state.include_subdomains);
6021 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276022}
6023
[email protected]316c1e5e2012-09-12 15:17:446024TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
6025 ASSERT_TRUE(test_server_.Start());
6026
6027 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196028 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6029 test_server_.GetURL("files/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366030 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196031 req->Start();
[email protected]255620da2013-08-19 13:14:296032 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446033
6034 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196035 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446036 EXPECT_EQ("text/html", mime_type);
6037
6038 std::string charset;
[email protected]f7022f32014-08-21 16:32:196039 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446040 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196041 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446042}
6043
[email protected]02494ec2014-05-07 15:05:296044TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346045 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346046 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346047 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026048 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346049
6050 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506051 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346052}
6053
[email protected]02494ec2014-05-07 15:05:296054#if !defined(DISABLE_FILE_SUPPORT)
6055TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6056 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6057 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456058 FileProtocolHandler file_protocol_handler(
6059 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296060 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6061
6062 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506063 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296064}
6065
[email protected]588614c22013-08-16 00:09:026066TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:446067 ASSERT_TRUE(test_server_.Start());
6068
6069 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196070 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366071 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY,
6072 &d));
[email protected]f7022f32014-08-21 16:32:196073 req->Start();
[email protected]255620da2013-08-19 13:14:296074 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446075
[email protected]f7022f32014-08-21 16:32:196076 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6077 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446078}
[email protected]02494ec2014-05-07 15:05:296079#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446080
[email protected]588614c22013-08-16 00:09:026081TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
6082 ASSERT_TRUE(test_server_.Start());
6083
6084 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196085 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366086 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY,
6087 &d));
[email protected]f7022f32014-08-21 16:32:196088 req->Start();
[email protected]588614c22013-08-16 00:09:026089 base::MessageLoop::current()->Run();
6090
[email protected]f7022f32014-08-21 16:32:196091 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6092 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:026093}
6094
[email protected]316c1e5e2012-09-12 15:17:446095TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
6096 ASSERT_TRUE(test_server_.Start());
6097
6098 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196099 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6100 test_server_.GetURL("files/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366101 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196102 req->Start();
[email protected]255620da2013-08-19 13:14:296103 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446104
[email protected]f7022f32014-08-21 16:32:196105 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6106 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446107}
6108
[email protected]e50efea2014-03-24 18:41:006109// Make sure redirects are cached, despite not reading their bodies.
6110TEST_F(URLRequestTestHTTP, CacheRedirect) {
6111 ASSERT_TRUE(test_server_.Start());
6112 GURL redirect_url =
6113 test_server_.GetURL("files/redirect302-to-echo-cacheable");
6114
6115 {
6116 TestDelegate d;
davidben151423e2015-03-23 18:48:366117 scoped_ptr<URLRequest> req(
6118 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196119 req->Start();
[email protected]e50efea2014-03-24 18:41:006120 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196121 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006122 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196123 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006124 }
6125
6126 {
6127 TestDelegate d;
6128 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:366129 scoped_ptr<URLRequest> req(
6130 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196131 req->Start();
[email protected]e50efea2014-03-24 18:41:006132 base::RunLoop().Run();
6133
6134 EXPECT_EQ(1, d.received_redirect_count());
6135 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196136 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006137
[email protected]f7022f32014-08-21 16:32:196138 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006139 base::RunLoop().Run();
6140 EXPECT_EQ(1, d.received_redirect_count());
6141 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196142 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6143 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006144 }
6145}
6146
6147// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6148// when the headers are read, since the body won't have been read.
6149TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
6150 ASSERT_TRUE(test_server_.Start());
6151 // URL that is normally cached.
6152 GURL initial_url = test_server_.GetURL("cachetime");
6153
6154 {
6155 // Set up the TestNetworkDelegate tp force a redirect.
6156 GURL redirect_to_url = test_server_.GetURL("echo");
6157 default_network_delegate_.set_redirect_on_headers_received_url(
6158 redirect_to_url);
6159
6160 TestDelegate d;
davidben151423e2015-03-23 18:48:366161 scoped_ptr<URLRequest> req(
6162 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196163 req->Start();
[email protected]e50efea2014-03-24 18:41:006164 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196165 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006166 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196167 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006168 }
6169
6170 {
6171 TestDelegate d;
davidben151423e2015-03-23 18:48:366172 scoped_ptr<URLRequest> req(
6173 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196174 req->Start();
[email protected]e50efea2014-03-24 18:41:006175 base::RunLoop().Run();
6176
[email protected]f7022f32014-08-21 16:32:196177 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6178 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006179 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196180 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006181 }
6182}
6183
[email protected]5f714132014-03-26 10:41:166184// Tests that redirection to an unsafe URL is allowed when it has been marked as
6185// safe.
6186TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
6187 ASSERT_TRUE(test_server_.Start());
6188
6189 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6190 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6191 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6192
6193 TestDelegate d;
6194 {
[email protected]f7022f32014-08-21 16:32:196195 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366196 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166197
[email protected]f7022f32014-08-21 16:32:196198 r->Start();
[email protected]5f714132014-03-26 10:41:166199 base::RunLoop().Run();
6200
[email protected]f7022f32014-08-21 16:32:196201 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:166202
[email protected]f7022f32014-08-21 16:32:196203 EXPECT_EQ(2U, r->url_chain().size());
6204 EXPECT_EQ(OK, r->status().error());
6205 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166206 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6207 }
6208}
6209
6210// Tests that a redirect to a different unsafe URL is blocked, even after adding
6211// some other URL to the whitelist.
6212TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
6213 ASSERT_TRUE(test_server_.Start());
6214
6215 GURL unsafe_url("data:text/html,something");
6216 GURL different_unsafe_url("data:text/html,something-else");
6217 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6218 default_network_delegate_.set_allowed_unsafe_redirect_url(
6219 different_unsafe_url);
6220
6221 TestDelegate d;
6222 {
[email protected]f7022f32014-08-21 16:32:196223 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366224 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166225
[email protected]f7022f32014-08-21 16:32:196226 r->Start();
[email protected]5f714132014-03-26 10:41:166227 base::RunLoop().Run();
6228
[email protected]f7022f32014-08-21 16:32:196229 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
6230 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:166231 }
6232}
6233
[email protected]5f714132014-03-26 10:41:166234// Redirects from an URL with fragment to an unsafe URL with fragment should
6235// be allowed, and the reference fragment of the target URL should be preserved.
6236TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
6237 ASSERT_TRUE(test_server_.Start());
6238
6239 GURL original_url(test_server_.GetURL("original#fragment1"));
6240 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6241 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6242
6243 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6244 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6245
6246 TestDelegate d;
6247 {
davidben151423e2015-03-23 18:48:366248 scoped_ptr<URLRequest> r(
6249 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166250
[email protected]f7022f32014-08-21 16:32:196251 r->Start();
[email protected]5f714132014-03-26 10:41:166252 base::RunLoop().Run();
6253
[email protected]f7022f32014-08-21 16:32:196254 EXPECT_EQ(2U, r->url_chain().size());
6255 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6256 EXPECT_EQ(OK, r->status().error());
6257 EXPECT_EQ(original_url, r->original_url());
6258 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166259 }
6260}
6261
6262// When a delegate has specified a safe redirect URL, but it does not match the
6263// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146264TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:166265 ASSERT_TRUE(test_server_.Start());
6266
6267 GURL original_url(test_server_.GetURL("original#expected-fragment"));
6268 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
6269 GURL redirect_url(test_server_.GetURL("target"));
6270 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
6271
6272 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6273 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6274
6275 TestDelegate d;
6276 {
davidben151423e2015-03-23 18:48:366277 scoped_ptr<URLRequest> r(
6278 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166279
[email protected]f7022f32014-08-21 16:32:196280 r->Start();
[email protected]5f714132014-03-26 10:41:166281 base::RunLoop().Run();
6282
[email protected]f7022f32014-08-21 16:32:196283 EXPECT_EQ(2U, r->url_chain().size());
6284 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6285 EXPECT_EQ(OK, r->status().error());
6286 EXPECT_EQ(original_url, r->original_url());
6287 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166288 }
6289}
6290
[email protected]f878230e2014-04-03 15:36:146291// When a delegate has specified a safe redirect URL, assume that the redirect
6292// URL should not be changed. In particular, the reference fragment should not
6293// be modified.
6294TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
6295 ASSERT_TRUE(test_server_.Start());
6296
6297 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
6298 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6299
6300 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6301 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6302
6303 TestDelegate d;
6304 {
davidben151423e2015-03-23 18:48:366305 scoped_ptr<URLRequest> r(
6306 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146307
[email protected]f7022f32014-08-21 16:32:196308 r->Start();
[email protected]f878230e2014-04-03 15:36:146309 base::RunLoop().Run();
6310
[email protected]f7022f32014-08-21 16:32:196311 EXPECT_EQ(2U, r->url_chain().size());
6312 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6313 EXPECT_EQ(OK, r->status().error());
6314 EXPECT_EQ(original_url, r->original_url());
6315 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146316 }
6317}
6318
6319// When a URLRequestRedirectJob is created, the redirection must be followed and
6320// the reference fragment of the target URL must not be modified.
6321TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
6322 ASSERT_TRUE(test_server_.Start());
6323
6324 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
6325 GURL redirect_url(test_server_.GetURL("echo"));
6326
6327 TestDelegate d;
davidben151423e2015-03-23 18:48:366328 scoped_ptr<URLRequest> r(
6329 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146330
6331 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196332 r.get(), &default_network_delegate_, redirect_url,
[email protected]f878230e2014-04-03 15:36:146333 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6334 AddTestInterceptor()->set_main_intercept_job(job);
6335
[email protected]f7022f32014-08-21 16:32:196336 r->Start();
[email protected]f878230e2014-04-03 15:36:146337 base::RunLoop().Run();
6338
[email protected]f7022f32014-08-21 16:32:196339 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6340 EXPECT_EQ(OK, r->status().error());
6341 EXPECT_EQ(original_url, r->original_url());
6342 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146343}
6344
[email protected]316c1e5e2012-09-12 15:17:446345TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
6346 ASSERT_TRUE(test_server_.Start());
6347
6348 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196349 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366350 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196351 req->SetReferrer("http://user:[email protected]/");
6352 req->Start();
[email protected]255620da2013-08-19 13:14:296353 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446354
6355 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6356}
6357
[email protected]99ecf6e2013-04-10 22:46:136358TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
6359 ASSERT_TRUE(test_server_.Start());
6360
6361 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196362 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366363 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196364 req->SetReferrer("http://foo.com/test#fragment");
6365 req->Start();
[email protected]255620da2013-08-19 13:14:296366 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136367
6368 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6369}
6370
6371TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
6372 ASSERT_TRUE(test_server_.Start());
6373
6374 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196375 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366376 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196377 req->SetReferrer("http://foo.com/test#fragment");
6378 req->SetReferrer("");
6379 req->Start();
[email protected]255620da2013-08-19 13:14:296380 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136381
6382 EXPECT_EQ(std::string("None"), d.data_received());
6383}
6384
[email protected]1826a402014-01-08 15:40:486385// Defer network start and then resume, checking that the request was a success
6386// and bytes were received.
6387TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
6388 ASSERT_TRUE(test_server_.Start());
6389
6390 TestDelegate d;
6391 {
6392 d.set_quit_on_network_start(true);
6393 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:366394 scoped_ptr<URLRequest> req(
6395 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486396
[email protected]f7022f32014-08-21 16:32:196397 req->Start();
[email protected]1826a402014-01-08 15:40:486398 base::RunLoop().Run();
6399
6400 EXPECT_EQ(1, d.received_before_network_start_count());
6401 EXPECT_EQ(0, d.response_started_count());
6402
[email protected]f7022f32014-08-21 16:32:196403 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486404 base::RunLoop().Run();
6405
6406 EXPECT_EQ(1, d.response_started_count());
6407 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196408 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486409 }
6410}
6411
6412// Check that OnBeforeNetworkStart is only called once even if there is a
6413// redirect.
6414TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
6415 ASSERT_TRUE(test_server_.Start());
6416
6417 TestDelegate d;
6418 {
6419 d.set_quit_on_redirect(true);
6420 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:196421 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366422 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486423
[email protected]f7022f32014-08-21 16:32:196424 req->Start();
[email protected]1826a402014-01-08 15:40:486425 base::RunLoop().Run();
6426
6427 EXPECT_EQ(1, d.received_before_network_start_count());
6428 EXPECT_EQ(0, d.response_started_count());
6429 EXPECT_EQ(0, d.received_redirect_count());
6430
[email protected]f7022f32014-08-21 16:32:196431 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486432 base::RunLoop().Run();
6433
6434 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196435 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:486436 base::RunLoop().Run();
6437
6438 // Check that the redirect's new network transaction does not get propagated
6439 // to a second OnBeforeNetworkStart() notification.
6440 EXPECT_EQ(1, d.received_before_network_start_count());
6441
6442 EXPECT_EQ(1, d.response_started_count());
6443 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196444 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486445 }
6446}
6447
6448// Cancel the request after learning that the request would use the network.
6449TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
6450 ASSERT_TRUE(test_server_.Start());
6451
6452 TestDelegate d;
6453 {
6454 d.set_quit_on_network_start(true);
6455 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:366456 scoped_ptr<URLRequest> req(
6457 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486458
[email protected]f7022f32014-08-21 16:32:196459 req->Start();
[email protected]1826a402014-01-08 15:40:486460 base::RunLoop().Run();
6461
6462 EXPECT_EQ(1, d.received_before_network_start_count());
6463 EXPECT_EQ(0, d.response_started_count());
6464
[email protected]f7022f32014-08-21 16:32:196465 req->Cancel();
[email protected]1826a402014-01-08 15:40:486466 base::RunLoop().Run();
6467
6468 EXPECT_EQ(1, d.response_started_count());
6469 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196470 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:486471 }
6472}
6473
[email protected]316c1e5e2012-09-12 15:17:446474TEST_F(URLRequestTestHTTP, CancelRedirect) {
6475 ASSERT_TRUE(test_server_.Start());
6476
6477 TestDelegate d;
6478 {
6479 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:196480 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366481 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196482 req->Start();
[email protected]255620da2013-08-19 13:14:296483 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446484
6485 EXPECT_EQ(1, d.response_started_count());
6486 EXPECT_EQ(0, d.bytes_received());
6487 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196488 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446489 }
6490}
6491
6492TEST_F(URLRequestTestHTTP, DeferredRedirect) {
6493 ASSERT_TRUE(test_server_.Start());
6494
6495 TestDelegate d;
6496 {
6497 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:046498 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366499 scoped_ptr<URLRequest> req(
6500 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046501
[email protected]f7022f32014-08-21 16:32:196502 req->Start();
[email protected]255620da2013-08-19 13:14:296503 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446504
6505 EXPECT_EQ(1, d.received_redirect_count());
6506
[email protected]f7022f32014-08-21 16:32:196507 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296508 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446509
6510 EXPECT_EQ(1, d.response_started_count());
6511 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196512 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446513
[email protected]6cdfd7f2013-02-08 20:40:156514 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446515 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476516 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446517 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6518
6519 std::string contents;
[email protected]82f84b92013-08-30 18:23:506520 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446521 EXPECT_EQ(contents, d.data_received());
6522 }
6523}
6524
[email protected]79e1fd62013-06-20 06:50:046525TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
6526 ASSERT_TRUE(test_server_.Start());
6527
6528 TestDelegate d;
6529 {
6530 d.set_quit_on_redirect(true);
6531 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366532 scoped_ptr<URLRequest> req(
6533 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046534
6535 EXPECT_FALSE(d.have_full_request_headers());
6536
[email protected]f7022f32014-08-21 16:32:196537 req->Start();
[email protected]255620da2013-08-19 13:14:296538 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046539
6540 EXPECT_EQ(1, d.received_redirect_count());
6541 EXPECT_TRUE(d.have_full_request_headers());
6542 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6543 d.ClearFullRequestHeaders();
6544
[email protected]f7022f32014-08-21 16:32:196545 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296546 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046547
6548 GURL target_url(test_server_.GetURL("files/with-headers.html"));
6549 EXPECT_EQ(1, d.response_started_count());
6550 EXPECT_TRUE(d.have_full_request_headers());
6551 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6552 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196553 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046554
6555 base::FilePath path;
6556 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476557 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046558 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6559
6560 std::string contents;
[email protected]82f84b92013-08-30 18:23:506561 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046562 EXPECT_EQ(contents, d.data_received());
6563 }
6564}
6565
[email protected]316c1e5e2012-09-12 15:17:446566TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
6567 ASSERT_TRUE(test_server_.Start());
6568
6569 TestDelegate d;
6570 {
6571 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196572 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366573 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196574 req->Start();
[email protected]255620da2013-08-19 13:14:296575 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446576
6577 EXPECT_EQ(1, d.received_redirect_count());
6578
[email protected]f7022f32014-08-21 16:32:196579 req->Cancel();
[email protected]255620da2013-08-19 13:14:296580 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446581
6582 EXPECT_EQ(1, d.response_started_count());
6583 EXPECT_EQ(0, d.bytes_received());
6584 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196585 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446586 }
6587}
6588
6589TEST_F(URLRequestTestHTTP, VaryHeader) {
6590 ASSERT_TRUE(test_server_.Start());
6591
[email protected]3b23a222013-05-15 21:33:256592 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446593 {
6594 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196595 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366596 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446597 HttpRequestHeaders headers;
6598 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196599 req->SetExtraRequestHeaders(headers);
6600 req->Start();
[email protected]255620da2013-08-19 13:14:296601 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256602
6603 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196604 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256605 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446606 }
6607
[email protected]3b23a222013-05-15 21:33:256608 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446609 {
6610 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196611 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366612 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446613 HttpRequestHeaders headers;
6614 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196615 req->SetExtraRequestHeaders(headers);
6616 req->Start();
[email protected]255620da2013-08-19 13:14:296617 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446618
[email protected]f7022f32014-08-21 16:32:196619 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256620
6621 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196622 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256623 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446624 }
6625
[email protected]3b23a222013-05-15 21:33:256626 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446627 {
6628 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196629 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366630 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446631 HttpRequestHeaders headers;
6632 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196633 req->SetExtraRequestHeaders(headers);
6634 req->Start();
[email protected]255620da2013-08-19 13:14:296635 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446636
[email protected]f7022f32014-08-21 16:32:196637 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256638
6639 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196640 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256641 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446642 }
6643}
6644
6645TEST_F(URLRequestTestHTTP, BasicAuth) {
6646 ASSERT_TRUE(test_server_.Start());
6647
6648 // populate the cache
6649 {
6650 TestDelegate d;
6651 d.set_credentials(AuthCredentials(kUser, kSecret));
6652
[email protected]f7022f32014-08-21 16:32:196653 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366654 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196655 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446656
[email protected]255620da2013-08-19 13:14:296657 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446658
6659 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6660 }
6661
6662 // repeat request with end-to-end validation. since auth-basic results in a
6663 // cachable page, we expect this test to result in a 304. in which case, the
6664 // response should be fetched from the cache.
6665 {
6666 TestDelegate d;
6667 d.set_credentials(AuthCredentials(kUser, kSecret));
6668
[email protected]f7022f32014-08-21 16:32:196669 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366670 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196671 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6672 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446673
[email protected]255620da2013-08-19 13:14:296674 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446675
6676 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6677
6678 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196679 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446680 }
6681}
6682
6683// Check that Set-Cookie headers in 401 responses are respected.
6684// http://crbug.com/6450
6685TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6686 ASSERT_TRUE(test_server_.Start());
6687
6688 GURL url_requiring_auth =
6689 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6690
6691 // Request a page that will give a 401 containing a Set-Cookie header.
6692 // Verify that when the transaction is restarted, it includes the new cookie.
6693 {
[email protected]ceefd7fd2012-11-29 00:36:246694 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446695 TestURLRequestContext context(true);
6696 context.set_network_delegate(&network_delegate);
6697 context.Init();
6698
6699 TestDelegate d;
6700 d.set_credentials(AuthCredentials(kUser, kSecret));
6701
davidben151423e2015-03-23 18:48:366702 scoped_ptr<URLRequest> r(
6703 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196704 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446705
[email protected]255620da2013-08-19 13:14:296706 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446707
6708 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6709
6710 // Make sure we sent the cookie in the restarted transaction.
6711 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6712 != std::string::npos);
6713 }
6714
6715 // Same test as above, except this time the restart is initiated earlier
6716 // (without user intervention since identity is embedded in the URL).
6717 {
[email protected]ceefd7fd2012-11-29 00:36:246718 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446719 TestURLRequestContext context(true);
6720 context.set_network_delegate(&network_delegate);
6721 context.Init();
6722
6723 TestDelegate d;
6724
6725 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186726 replacements.SetUsernameStr("user2");
6727 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446728 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6729
davidben151423e2015-03-23 18:48:366730 scoped_ptr<URLRequest> r(
6731 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196732 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446733
[email protected]255620da2013-08-19 13:14:296734 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446735
6736 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6737
6738 // Make sure we sent the cookie in the restarted transaction.
6739 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6740 != std::string::npos);
6741 }
6742}
6743
[email protected]58e32bb2013-01-21 18:23:256744// Tests that load timing works as expected with auth and the cache.
6745TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6746 ASSERT_TRUE(test_server_.Start());
6747
6748 // populate the cache
6749 {
6750 TestDelegate d;
6751 d.set_credentials(AuthCredentials(kUser, kSecret));
6752
[email protected]f7022f32014-08-21 16:32:196753 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366754 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196755 r->Start();
[email protected]58e32bb2013-01-21 18:23:256756
[email protected]255620da2013-08-19 13:14:296757 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256758
6759 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6760
6761 LoadTimingInfo load_timing_info_before_auth;
6762 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6763 &load_timing_info_before_auth));
6764 TestLoadTimingNotReused(load_timing_info_before_auth,
6765 CONNECT_TIMING_HAS_DNS_TIMES);
6766
6767 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196768 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256769 // The test server does not support keep alive sockets, so the second
6770 // request with auth should use a new socket.
6771 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6772 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6773 load_timing_info.socket_log_id);
6774 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6775 load_timing_info.connect_timing.connect_start);
6776 }
6777
[email protected]3b23a222013-05-15 21:33:256778 // Repeat request with end-to-end validation. Since auth-basic results in a
6779 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256780 // response should be fetched from the cache.
6781 {
6782 TestDelegate d;
6783 d.set_credentials(AuthCredentials(kUser, kSecret));
6784
[email protected]f7022f32014-08-21 16:32:196785 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366786 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196787 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6788 r->Start();
[email protected]58e32bb2013-01-21 18:23:256789
[email protected]255620da2013-08-19 13:14:296790 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256791
6792 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6793
6794 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196795 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256796
[email protected]3b23a222013-05-15 21:33:256797 // Since there was a request that went over the wire, the load timing
6798 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256799 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196800 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256801 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256802 }
6803}
6804
[email protected]316c1e5e2012-09-12 15:17:446805// In this test, we do a POST which the server will 302 redirect.
6806// The subsequent transaction should use GET, and should not send the
6807// Content-Type header.
6808// http://code.google.com/p/chromium/issues/detail?id=843
6809TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6810 ASSERT_TRUE(test_server_.Start());
6811
6812 const char kData[] = "hello world";
6813
6814 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196815 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366816 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196817 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076818 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446819
6820 // Set headers (some of which are specific to the POST).
6821 HttpRequestHeaders headers;
6822 headers.AddHeadersFromString(
6823 "Content-Type: multipart/form-data; "
6824 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6825 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6826 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6827 "Accept-Language: en-US,en\r\n"
6828 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6829 "Content-Length: 11\r\n"
6830 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196831 req->SetExtraRequestHeaders(headers);
6832 req->Start();
[email protected]255620da2013-08-19 13:14:296833 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446834
6835 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196836 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446837 EXPECT_EQ("text/html", mime_type);
6838
6839 const std::string& data = d.data_received();
6840
6841 // Check that the post-specific headers were stripped:
6842 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6843 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6844 EXPECT_FALSE(ContainsString(data, "Origin:"));
6845
6846 // These extra request headers should not have been stripped.
6847 EXPECT_TRUE(ContainsString(data, "Accept:"));
6848 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6849 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6850}
6851
jww5fe460ff2015-03-28 00:22:516852// The following tests check that we handle mutating the request for HTTP
6853// redirects as expected.
6854// See https://crbug.com/56373, https://crbug.com/102130, and
6855// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:446856
6857TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6858 ASSERT_TRUE(test_server_.Start());
6859
6860 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:516861 const GURL https_redirect_url =
6862 test_server_.GetURL("files/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:446863
6864 HTTPRedirectMethodTest(url, "POST", "GET", true);
6865 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6866 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516867
6868 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6869 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6870 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6871 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6872 std::string());
[email protected]316c1e5e2012-09-12 15:17:446873}
6874
6875TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6876 ASSERT_TRUE(test_server_.Start());
6877
6878 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:516879 const GURL https_redirect_url =
6880 test_server_.GetURL("files/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:446881
6882 HTTPRedirectMethodTest(url, "POST", "GET", true);
6883 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6884 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516885
6886 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6887 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6888 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6889 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6890 std::string());
[email protected]316c1e5e2012-09-12 15:17:446891}
6892
6893TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6894 ASSERT_TRUE(test_server_.Start());
6895
6896 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:516897 const GURL https_redirect_url =
6898 test_server_.GetURL("files/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:446899
6900 HTTPRedirectMethodTest(url, "POST", "GET", true);
6901 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6902 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516903
6904 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6905 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6906 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6907 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6908 std::string());
[email protected]316c1e5e2012-09-12 15:17:446909}
6910
6911TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6912 ASSERT_TRUE(test_server_.Start());
6913
6914 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:516915 const GURL https_redirect_url =
6916 test_server_.GetURL("files/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:446917
6918 HTTPRedirectMethodTest(url, "POST", "POST", true);
6919 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6920 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516921
6922 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6923 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6924 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6925 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:446926}
6927
[email protected]0a17aab32014-04-24 03:32:376928TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6929 ASSERT_TRUE(test_server_.Start());
6930
6931 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:516932 const GURL https_redirect_url =
6933 test_server_.GetURL("files/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:376934
6935 HTTPRedirectMethodTest(url, "POST", "POST", true);
6936 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6937 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516938
6939 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6940 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6941 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6942 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:376943}
6944
6945// Make sure that 308 responses without bodies are not treated as redirects.
6946// Certain legacy apis that pre-date the response code expect this behavior
6947// (Like Google Drive).
6948TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6949 ASSERT_TRUE(test_server_.Start());
6950
6951 TestDelegate d;
6952 const GURL url = test_server_.GetURL("files/308-without-location-header");
6953
davidben151423e2015-03-23 18:48:366954 scoped_ptr<URLRequest> request(
6955 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:376956
[email protected]f7022f32014-08-21 16:32:196957 request->Start();
[email protected]0a17aab32014-04-24 03:32:376958 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196959 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6960 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:376961 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196962 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:376963 EXPECT_EQ("This is not a redirect.", d.data_received());
6964}
6965
[email protected]f878230e2014-04-03 15:36:146966TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6967 ASSERT_TRUE(test_server_.Start());
6968
6969 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6970 GURL expected_url(test_server_.GetURL("echo#fragment"));
6971
6972 TestDelegate d;
6973 {
davidben151423e2015-03-23 18:48:366974 scoped_ptr<URLRequest> r(
6975 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146976
[email protected]f7022f32014-08-21 16:32:196977 r->Start();
[email protected]f878230e2014-04-03 15:36:146978 base::RunLoop().Run();
6979
[email protected]f7022f32014-08-21 16:32:196980 EXPECT_EQ(2U, r->url_chain().size());
6981 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6982 EXPECT_EQ(OK, r->status().error());
6983 EXPECT_EQ(original_url, r->original_url());
6984 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:146985 }
6986}
6987
[email protected]cba24642014-08-15 20:49:596988TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6989 ASSERT_TRUE(test_server_.Start());
6990
6991 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6992 GURL first_party_url("http://example.com");
6993
6994 TestDelegate d;
6995 {
davidben151423e2015-03-23 18:48:366996 scoped_ptr<URLRequest> r(
6997 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196998 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:596999
[email protected]f7022f32014-08-21 16:32:197000 r->Start();
[email protected]cba24642014-08-15 20:49:597001 base::RunLoop().Run();
7002
[email protected]f7022f32014-08-21 16:32:197003 EXPECT_EQ(2U, r->url_chain().size());
7004 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7005 EXPECT_EQ(OK, r->status().error());
7006 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597007 }
7008}
7009
7010TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
7011 ASSERT_TRUE(test_server_.Start());
7012
7013 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
7014 GURL original_first_party_url("http://example.com");
7015 GURL expected_first_party_url(test_server_.GetURL("echo"));
7016
7017 TestDelegate d;
7018 {
davidben151423e2015-03-23 18:48:367019 scoped_ptr<URLRequest> r(
7020 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197021 r->set_first_party_for_cookies(original_first_party_url);
7022 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597023 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7024
[email protected]f7022f32014-08-21 16:32:197025 r->Start();
[email protected]cba24642014-08-15 20:49:597026 base::RunLoop().Run();
7027
[email protected]f7022f32014-08-21 16:32:197028 EXPECT_EQ(2U, r->url_chain().size());
7029 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7030 EXPECT_EQ(OK, r->status().error());
7031 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597032 }
7033}
7034
[email protected]316c1e5e2012-09-12 15:17:447035TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
7036 ASSERT_TRUE(test_server_.Start());
7037
7038 const char kData[] = "hello world";
7039
7040 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197041 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367042 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197043 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077044 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447045 HttpRequestHeaders headers;
7046 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517047 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197048 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447049
7050 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197051 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:097052 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:447053 AddTestInterceptor()->set_main_intercept_job(job);
7054
[email protected]f7022f32014-08-21 16:32:197055 req->Start();
[email protected]255620da2013-08-19 13:14:297056 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197057 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447058}
7059
7060TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
7061 ASSERT_TRUE(test_server_.Start());
7062
7063 const char kData[] = "hello world";
7064
7065 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197066 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367067 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197068 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077069 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447070 HttpRequestHeaders headers;
7071 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517072 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197073 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447074
7075 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197076 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:097077 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
7078 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:447079 AddTestInterceptor()->set_main_intercept_job(job);
7080
[email protected]f7022f32014-08-21 16:32:197081 req->Start();
[email protected]255620da2013-08-19 13:14:297082 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197083 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447084 EXPECT_EQ(kData, d.data_received());
7085}
7086
7087// Check that default A-L header is sent.
7088TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
7089 ASSERT_TRUE(test_server_.Start());
7090
[email protected]8790210c2013-12-02 05:29:537091 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247092 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447093 TestURLRequestContext context(true);
7094 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437095 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447096 context.Init();
7097
7098 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197099 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:367100 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197101 req->Start();
[email protected]255620da2013-08-19 13:14:297102 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447103 EXPECT_EQ("en", d.data_received());
7104}
7105
7106// Check that an empty A-L header is not sent. http://crbug.com/77365.
7107TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
7108 ASSERT_TRUE(test_server_.Start());
7109
[email protected]8790210c2013-12-02 05:29:537110 std::string empty_string; // Avoid most vexing parse on line below.
7111 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247112 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447113 TestURLRequestContext context(true);
7114 context.set_network_delegate(&network_delegate);
7115 context.Init();
7116 // We override the language after initialization because empty entries
7117 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437118 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447119
7120 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197121 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:367122 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197123 req->Start();
[email protected]255620da2013-08-19 13:14:297124 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447125 EXPECT_EQ("None", d.data_received());
7126}
7127
7128// Check that if request overrides the A-L header, the default is not appended.
7129// See http://crbug.com/20894
7130TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
7131 ASSERT_TRUE(test_server_.Start());
7132
7133 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197134 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367135 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447136 HttpRequestHeaders headers;
7137 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197138 req->SetExtraRequestHeaders(headers);
7139 req->Start();
[email protected]255620da2013-08-19 13:14:297140 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447141 EXPECT_EQ(std::string("ru"), d.data_received());
7142}
7143
7144// Check that default A-E header is sent.
7145TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
7146 ASSERT_TRUE(test_server_.Start());
7147
7148 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197149 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367150 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447151 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197152 req->SetExtraRequestHeaders(headers);
7153 req->Start();
[email protected]255620da2013-08-19 13:14:297154 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447155 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7156}
7157
7158// Check that if request overrides the A-E header, the default is not appended.
7159// See http://crbug.com/47381
7160TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
7161 ASSERT_TRUE(test_server_.Start());
7162
7163 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197164 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367165 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447166 HttpRequestHeaders headers;
7167 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197168 req->SetExtraRequestHeaders(headers);
7169 req->Start();
[email protected]255620da2013-08-19 13:14:297170 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447171 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7172 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7173}
7174
[email protected]84f05432013-03-15 01:00:127175// Check that setting the A-C header sends the proper header.
7176TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:447177 ASSERT_TRUE(test_server_.Start());
7178
7179 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197180 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367181 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447182 HttpRequestHeaders headers;
7183 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197184 req->SetExtraRequestHeaders(headers);
7185 req->Start();
[email protected]255620da2013-08-19 13:14:297186 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447187 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7188}
7189
7190// Check that default User-Agent header is sent.
7191TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
7192 ASSERT_TRUE(test_server_.Start());
7193
7194 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197195 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367196 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197197 req->Start();
[email protected]255620da2013-08-19 13:14:297198 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197199 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377200 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447201}
7202
7203// Check that if request overrides the User-Agent header,
7204// the default is not appended.
7205TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
7206 ASSERT_TRUE(test_server_.Start());
7207
7208 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197209 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367210 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447211 HttpRequestHeaders headers;
7212 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197213 req->SetExtraRequestHeaders(headers);
7214 req->Start();
[email protected]255620da2013-08-19 13:14:297215 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357216 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447217}
7218
[email protected]ee4c30d2012-11-07 15:08:437219// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7220// User-Agent header to be sent but does not send the Accept-Language and
7221// Accept-Charset headers.
7222TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
7223 ASSERT_TRUE(test_server_.Start());
7224
[email protected]ceefd7fd2012-11-29 00:36:247225 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437226 TestURLRequestContext context(true);
7227 context.set_network_delegate(&network_delegate);
7228 context.Init();
7229 // We override the HttpUserAgentSettings after initialization because empty
7230 // entries get overridden by Init().
7231 context.set_http_user_agent_settings(NULL);
7232
7233 struct {
7234 const char* request;
7235 const char* expected_response;
7236 } tests[] = { { "echoheader?Accept-Language", "None" },
7237 { "echoheader?Accept-Charset", "None" },
7238 { "echoheader?User-Agent", "" } };
7239
viettrungluue4a8b882014-10-16 06:17:387240 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437241 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197242 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:367243 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197244 req->Start();
[email protected]255620da2013-08-19 13:14:297245 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437246 EXPECT_EQ(tests[i].expected_response, d.data_received())
7247 << " Request = \"" << tests[i].request << "\"";
7248 }
7249}
7250
[email protected]5033ab82013-03-22 20:17:467251// Make sure that URLRequest passes on its priority updates to
7252// newly-created jobs after the first one.
7253TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
7254 ASSERT_TRUE(test_server_.Start());
7255
7256 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197257 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367258 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197259 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467260
7261 scoped_refptr<URLRequestRedirectJob> redirect_job =
7262 new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197263 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:097264 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:507265 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:467266
[email protected]f7022f32014-08-21 16:32:197267 req->SetPriority(LOW);
7268 req->Start();
7269 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467270
7271 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:197272 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:507273 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:467274
7275 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297276 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:467277 EXPECT_EQ(LOW, job->priority());
7278}
7279
[email protected]80abdad2014-03-15 00:20:547280// Check that creating a network request while entering/exiting suspend mode
7281// fails as it should. This is the only case where an HttpTransactionFactory
7282// does not return an HttpTransaction.
7283TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7284 // Create a new HttpNetworkLayer that thinks it's suspended.
7285 HttpNetworkSession::Params params;
7286 params.host_resolver = default_context_.host_resolver();
7287 params.cert_verifier = default_context_.cert_verifier();
7288 params.transport_security_state = default_context_.transport_security_state();
7289 params.proxy_service = default_context_.proxy_service();
7290 params.ssl_config_service = default_context_.ssl_config_service();
7291 params.http_auth_handler_factory =
7292 default_context_.http_auth_handler_factory();
7293 params.network_delegate = &default_network_delegate_;
7294 params.http_server_properties = default_context_.http_server_properties();
mmenkee65e7af2015-10-13 17:16:427295 HttpNetworkSession network_session(params);
[email protected]80abdad2014-03-15 00:20:547296 scoped_ptr<HttpNetworkLayer> network_layer(
mmenkee65e7af2015-10-13 17:16:427297 new HttpNetworkLayer(&network_session));
[email protected]80abdad2014-03-15 00:20:547298 network_layer->OnSuspend();
7299
7300 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
mmenkee65e7af2015-10-13 17:16:427301 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547302
7303 TestURLRequestContext context(true);
7304 context.set_http_transaction_factory(&http_cache);
7305 context.Init();
7306
7307 TestDelegate d;
davidben151423e2015-03-23 18:48:367308 scoped_ptr<URLRequest> req(
7309 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197310 req->Start();
[email protected]80abdad2014-03-15 00:20:547311 base::RunLoop().Run();
7312
7313 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197314 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7315 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547316}
7317
7318// Check that creating a network request while entering/exiting suspend mode
7319// fails as it should in the case there is no cache. This is the only case
7320// where an HttpTransactionFactory does not return an HttpTransaction.
7321TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
7322 // Create a new HttpNetworkLayer that thinks it's suspended.
7323 HttpNetworkSession::Params params;
7324 params.host_resolver = default_context_.host_resolver();
7325 params.cert_verifier = default_context_.cert_verifier();
7326 params.transport_security_state = default_context_.transport_security_state();
7327 params.proxy_service = default_context_.proxy_service();
7328 params.ssl_config_service = default_context_.ssl_config_service();
7329 params.http_auth_handler_factory =
7330 default_context_.http_auth_handler_factory();
7331 params.network_delegate = &default_network_delegate_;
7332 params.http_server_properties = default_context_.http_server_properties();
mmenkee65e7af2015-10-13 17:16:427333 HttpNetworkSession network_session(params);
7334 HttpNetworkLayer network_layer(&network_session);
[email protected]80abdad2014-03-15 00:20:547335 network_layer.OnSuspend();
7336
7337 TestURLRequestContext context(true);
7338 context.set_http_transaction_factory(&network_layer);
7339 context.Init();
7340
7341 TestDelegate d;
davidben151423e2015-03-23 18:48:367342 scoped_ptr<URLRequest> req(
7343 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197344 req->Start();
[email protected]80abdad2014-03-15 00:20:547345 base::RunLoop().Run();
7346
7347 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197348 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7349 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547350}
7351
ttuttlec0c828492015-05-15 01:25:557352TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
7353 ASSERT_TRUE(test_server_.Start());
7354
7355 TestDelegate d;
7356 GURL test_url(test_server_.GetURL(std::string()));
7357 scoped_ptr<URLRequest> req(
7358 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7359
7360 req->Start();
7361 base::RunLoop().Run();
7362
7363 EXPECT_TRUE(req->response_info().network_accessed);
7364}
7365
7366TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
7367 ASSERT_TRUE(test_server_.Start());
7368
7369 // Populate the cache.
7370 TestDelegate d;
7371 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
7372 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
7373 req->Start();
7374 base::RunLoop().Run();
7375
7376 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7377 EXPECT_TRUE(req->response_info().network_accessed);
7378 EXPECT_FALSE(req->response_info().was_cached);
7379
7380 req = default_context_.CreateRequest(test_server_.GetURL("cachetime"),
7381 DEFAULT_PRIORITY, &d);
7382 req->Start();
7383 base::RunLoop().Run();
7384
7385 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7386 EXPECT_FALSE(req->response_info().network_accessed);
7387 EXPECT_TRUE(req->response_info().was_cached);
7388}
7389
7390TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
7391 ASSERT_TRUE(test_server_.Start());
7392
7393 TestDelegate d;
7394 GURL test_url(test_server_.GetURL(std::string()));
7395 scoped_ptr<URLRequest> req(
7396 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7397 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7398
7399 req->Start();
7400 base::RunLoop().Run();
7401
7402 EXPECT_FALSE(req->response_info().network_accessed);
7403}
7404
bengr1bf8e942014-11-07 01:36:507405class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7406 public:
7407 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7408 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7409 // tests into the factory tests.
7410 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7411 }
7412
7413 void SetUpFactory() override {
7414 interceptor_ = new MockURLRequestInterceptor();
7415 job_factory_.reset(new URLRequestInterceptingJobFactory(
7416 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
7417 }
7418
7419 MockURLRequestInterceptor* interceptor() const {
7420 return interceptor_;
7421 }
7422
7423 private:
7424 MockURLRequestInterceptor* interceptor_;
7425};
7426
7427TEST_F(URLRequestInterceptorTestHTTP,
7428 NetworkDelegateNotificationOnRedirectIntercept) {
7429 interceptor()->set_intercept_redirect(true);
7430 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7431 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7432
7433 ASSERT_TRUE(test_server()->Start());
7434
7435 TestDelegate d;
7436 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:367437 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507438 req->Start();
7439 base::RunLoop().Run();
7440
7441 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7442 // Check we got one good response
7443 EXPECT_TRUE(req->status().is_success());
7444 if (req->status().is_success())
7445 EXPECT_EQ(200, req->response_headers()->response_code());
7446
7447 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7448 EXPECT_EQ(1, d.response_started_count());
7449 EXPECT_EQ(0, d.received_redirect_count());
7450
7451 EXPECT_EQ(1, default_network_delegate()->created_requests());
7452 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7453 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7454}
7455
7456TEST_F(URLRequestInterceptorTestHTTP,
7457 NetworkDelegateNotificationOnErrorIntercept) {
7458 // Intercept that error and respond with an OK response.
7459 interceptor()->set_intercept_final_response(true);
7460 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7461 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7462 default_network_delegate()->set_can_be_intercepted_on_error(true);
7463
7464 ASSERT_TRUE(test_server()->Start());
7465
7466 TestDelegate d;
7467 scoped_ptr<URLRequest> req(default_context().CreateRequest(
7468 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:367469 &d));
bengr1bf8e942014-11-07 01:36:507470 req->set_method("GET");
7471 req->Start();
7472 base::RunLoop().Run();
7473
7474 EXPECT_TRUE(interceptor()->did_intercept_final());
7475
7476 // Check we received one good response.
7477 EXPECT_TRUE(req->status().is_success());
7478 if (req->status().is_success())
7479 EXPECT_EQ(200, req->response_headers()->response_code());
7480 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7481 EXPECT_EQ(1, d.response_started_count());
7482 EXPECT_EQ(0, d.received_redirect_count());
7483
7484 EXPECT_EQ(1, default_network_delegate()->created_requests());
7485 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7486 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7487}
7488
7489TEST_F(URLRequestInterceptorTestHTTP,
7490 NetworkDelegateNotificationOnResponseIntercept) {
7491 // Intercept that error and respond with an OK response.
7492 interceptor()->set_intercept_final_response(true);
7493
7494 // Intercept with a real URLRequestHttpJob.
7495 interceptor()->set_use_url_request_http_job(true);
7496
7497 ASSERT_TRUE(test_server()->Start());
7498
7499 TestDelegate d;
7500 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:367501 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507502 req->set_method("GET");
7503 req->Start();
7504 base::RunLoop().Run();
7505
7506 EXPECT_TRUE(interceptor()->did_intercept_final());
7507
7508 // Check we received one good response.
7509 EXPECT_TRUE(req->status().is_success());
7510 if (req->status().is_success())
7511 EXPECT_EQ(200, req->response_headers()->response_code());
7512 EXPECT_EQ("hello", d.data_received());
7513 EXPECT_EQ(1, d.response_started_count());
7514 EXPECT_EQ(0, d.received_redirect_count());
7515
7516 EXPECT_EQ(1, default_network_delegate()->created_requests());
7517 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7518 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7519}
7520
mkwst0c5eab872014-11-21 14:18:547521class URLRequestTestReferrerPolicy : public URLRequestTest {
7522 public:
7523 URLRequestTestReferrerPolicy() {}
7524
7525 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
7526 origin_server_.reset(new SpawnedTestServer(
7527 origin_type, SpawnedTestServer::kLocalhost,
7528 origin_type == SpawnedTestServer::TYPE_HTTPS
7529 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477530 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547531 ASSERT_TRUE(origin_server_->Start());
7532 }
7533
7534 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
7535 SpawnedTestServer::Type destination_type) {
7536 origin_server_.reset(new SpawnedTestServer(
7537 origin_type, SpawnedTestServer::kLocalhost,
7538 origin_type == SpawnedTestServer::TYPE_HTTPS
7539 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477540 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547541 ASSERT_TRUE(origin_server_->Start());
7542
7543 destination_server_.reset(new SpawnedTestServer(
7544 destination_type, SpawnedTestServer::kLocalhost,
7545 destination_type == SpawnedTestServer::TYPE_HTTPS
7546 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477547 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547548 ASSERT_TRUE(destination_server_->Start());
7549 }
7550
7551 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7552 const GURL& referrer,
7553 const GURL& expected) {
7554 // Create and execute the request: we'll only have a |destination_server_|
7555 // if the origins are meant to be distinct. Otherwise, we'll use the
7556 // |origin_server_| for both endpoints.
7557 GURL destination_url =
7558 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
7559 : origin_server_->GetURL("echoheader?Referer");
7560 GURL origin_url =
7561 origin_server_->GetURL("server-redirect?" + destination_url.spec());
7562
7563 TestDelegate d;
7564 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367565 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547566 req->set_referrer_policy(policy);
7567 req->SetReferrer(referrer.spec());
7568 req->Start();
7569 base::RunLoop().Run();
7570
7571 EXPECT_EQ(1, d.response_started_count());
7572 EXPECT_EQ(1, d.received_redirect_count());
7573 EXPECT_EQ(destination_url, req->url());
7574 EXPECT_TRUE(req->status().is_success());
7575 EXPECT_EQ(200, req->response_headers()->response_code());
7576
7577 EXPECT_EQ(expected.spec(), req->referrer());
7578 if (expected.is_empty())
7579 EXPECT_EQ("None", d.data_received());
7580 else
7581 EXPECT_EQ(expected.spec(), d.data_received());
7582 }
7583
7584 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
7585
7586 private:
7587 scoped_ptr<SpawnedTestServer> origin_server_;
7588 scoped_ptr<SpawnedTestServer> destination_server_;
7589};
7590
7591TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
7592 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
7593
7594 VerifyReferrerAfterRedirect(
7595 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7596 origin_server()->GetURL("path/to/file.html"),
7597 origin_server()->GetURL("path/to/file.html"));
7598
7599 VerifyReferrerAfterRedirect(
7600 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7601 origin_server()->GetURL("path/to/file.html"),
7602 origin_server()->GetURL("path/to/file.html"));
7603
7604 VerifyReferrerAfterRedirect(
7605 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7606 origin_server()->GetURL("path/to/file.html"),
7607 origin_server()->GetURL("path/to/file.html"));
7608
7609 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7610 origin_server()->GetURL("path/to/file.html"),
7611 origin_server()->GetURL("path/to/file.html"));
7612}
7613
tfarinae04a95b2015-09-18 22:48:127614// Can't spin up more than one SpawnedTestServer on Android.
7615#if defined(OS_ANDROID)
7616#define MAYBE_HTTPToCrossOriginHTTP DISABLED_HTTPToCrosOriginHTTP
7617#else
7618#define MAYBE_HTTPToCrossOriginHTTP HTTPToCrossOriginHTTP
7619#endif
7620TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPToCrossOriginHTTP) {
mkwst0c5eab872014-11-21 14:18:547621 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7622 SpawnedTestServer::TYPE_HTTP);
7623
7624 VerifyReferrerAfterRedirect(
7625 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7626 origin_server()->GetURL("path/to/file.html"),
7627 origin_server()->GetURL("path/to/file.html"));
7628
7629 VerifyReferrerAfterRedirect(
7630 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7631 origin_server()->GetURL("path/to/file.html"),
7632 origin_server()->GetURL(std::string()));
7633
7634 VerifyReferrerAfterRedirect(
7635 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7636 origin_server()->GetURL("path/to/file.html"),
7637 origin_server()->GetURL(std::string()));
7638
7639 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7640 origin_server()->GetURL("path/to/file.html"),
7641 origin_server()->GetURL("path/to/file.html"));
7642}
7643
7644TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
7645 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
7646
7647 VerifyReferrerAfterRedirect(
7648 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7649 origin_server()->GetURL("path/to/file.html"),
7650 origin_server()->GetURL("path/to/file.html"));
7651
7652 VerifyReferrerAfterRedirect(
7653 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7654 origin_server()->GetURL("path/to/file.html"),
7655 origin_server()->GetURL("path/to/file.html"));
7656
7657 VerifyReferrerAfterRedirect(
7658 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7659 origin_server()->GetURL("path/to/file.html"),
7660 origin_server()->GetURL("path/to/file.html"));
7661
7662 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7663 origin_server()->GetURL("path/to/file.html"),
7664 origin_server()->GetURL("path/to/file.html"));
7665}
7666
tfarinae04a95b2015-09-18 22:48:127667// Can't spin up more than one SpawnedTestServer on Android.
7668#if defined(OS_ANDROID)
7669#define MAYBE_HTTPSToCrossOriginHTTPS DISABLED_HTTPSToCrosOriginHTTPS
7670#else
7671#define MAYBE_HTTPSToCrossOriginHTTPS HTTPSToCrossOriginHTTPS
7672#endif
7673TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPSToCrossOriginHTTPS) {
mkwst0c5eab872014-11-21 14:18:547674 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7675 SpawnedTestServer::TYPE_HTTPS);
7676
7677 VerifyReferrerAfterRedirect(
7678 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7679 origin_server()->GetURL("path/to/file.html"),
7680 origin_server()->GetURL("path/to/file.html"));
7681
7682 VerifyReferrerAfterRedirect(
7683 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7684 origin_server()->GetURL("path/to/file.html"),
7685 origin_server()->GetURL(std::string()));
7686
7687 VerifyReferrerAfterRedirect(
7688 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7689 origin_server()->GetURL("path/to/file.html"),
7690 origin_server()->GetURL(std::string()));
7691
7692 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7693 origin_server()->GetURL("path/to/file.html"),
7694 origin_server()->GetURL("path/to/file.html"));
7695}
7696
tfarinae04a95b2015-09-18 22:48:127697// Can't spin up more than one SpawnedTestServer on Android.
7698#if defined(OS_ANDROID)
7699#define MAYBE_HTTPToHTTPS DISABLED_HTTPToHTTPS
7700#else
7701#define MAYBE_HTTPToHTTPS HTTPToHTTPS
7702#endif
7703TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPToHTTPS) {
mkwst0c5eab872014-11-21 14:18:547704 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7705 SpawnedTestServer::TYPE_HTTPS);
7706
7707 VerifyReferrerAfterRedirect(
7708 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7709 origin_server()->GetURL("path/to/file.html"),
7710 origin_server()->GetURL("path/to/file.html"));
7711
7712 VerifyReferrerAfterRedirect(
7713 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7714 origin_server()->GetURL("path/to/file.html"),
7715 origin_server()->GetURL(std::string()));
7716
7717 VerifyReferrerAfterRedirect(
7718 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7719 origin_server()->GetURL("path/to/file.html"),
7720 origin_server()->GetURL(std::string()));
7721
7722 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7723 origin_server()->GetURL("path/to/file.html"),
7724 origin_server()->GetURL("path/to/file.html"));
7725}
7726
tfarinae04a95b2015-09-18 22:48:127727// Can't spin up more than one SpawnedTestServer on Android.
7728#if defined(OS_ANDROID)
7729#define MAYBE_HTTPSToHTTP DISABLED_HTTPSToHTTP
7730#else
7731#define MAYBE_HTTPSToHTTP HTTPSToHTTP
7732#endif
7733TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPSToHTTP) {
mkwst0c5eab872014-11-21 14:18:547734 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7735 SpawnedTestServer::TYPE_HTTP);
7736
7737 VerifyReferrerAfterRedirect(
7738 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7739 origin_server()->GetURL("path/to/file.html"), GURL());
7740
7741 VerifyReferrerAfterRedirect(
7742 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7743 origin_server()->GetURL("path/to/file.html"), GURL());
7744
7745 VerifyReferrerAfterRedirect(
7746 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7747 origin_server()->GetURL("path/to/file.html"),
7748 origin_server()->GetURL(std::string()));
7749
7750 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7751 origin_server()->GetURL("path/to/file.html"),
7752 origin_server()->GetURL("path/to/file.html"));
7753}
7754
[email protected]73e0bba2009-02-19 22:57:097755class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507756 public:
[email protected]ef2bf422012-05-11 03:27:097757 HTTPSRequestTest() : default_context_(true) {
7758 default_context_.set_network_delegate(&default_network_delegate_);
7759 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507760 }
dcheng67be2b1f2014-10-27 21:47:297761 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507762
7763 protected:
[email protected]ceefd7fd2012-11-29 00:36:247764 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097765 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467766};
7767
[email protected]c044616e2013-02-20 02:01:267768TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227769 SpawnedTestServer test_server(
7770 SpawnedTestServer::TYPE_HTTPS,
7771 SpawnedTestServer::kLocalhost,
7772 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117773 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467774
[email protected]ea224582008-12-07 20:25:467775 TestDelegate d;
7776 {
[email protected]f7022f32014-08-21 16:32:197777 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367778 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197779 r->Start();
7780 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467781
[email protected]255620da2013-08-19 13:14:297782 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467783
7784 EXPECT_EQ(1, d.response_started_count());
7785 EXPECT_FALSE(d.received_data_before_response());
7786 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197787 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197788 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197789 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197790 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197791 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467792 }
[email protected]ea224582008-12-07 20:25:467793}
7794
[email protected]5774ada2010-07-15 06:30:547795TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227796 SpawnedTestServer::SSLOptions ssl_options(
7797 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7798 SpawnedTestServer test_server(
7799 SpawnedTestServer::TYPE_HTTPS,
7800 ssl_options,
7801 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117802 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337803
7804 bool err_allowed = true;
7805 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7806 TestDelegate d;
7807 {
7808 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197809 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367810 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337811
[email protected]f7022f32014-08-21 16:32:197812 r->Start();
7813 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337814
[email protected]255620da2013-08-19 13:14:297815 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337816
7817 EXPECT_EQ(1, d.response_started_count());
7818 EXPECT_FALSE(d.received_data_before_response());
7819 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177820 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337821 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197822 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177823 } else {
[email protected]bacff652009-03-31 17:50:337824 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177825 }
[email protected]bacff652009-03-31 17:50:337826 }
7827 }
7828}
7829
[email protected]5774ada2010-07-15 06:30:547830TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227831 SpawnedTestServer::SSLOptions ssl_options(
7832 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7833 SpawnedTestServer test_server(
7834 SpawnedTestServer::TYPE_HTTPS,
7835 ssl_options,
7836 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117837 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337838
7839 // Iterate from false to true, just so that we do the opposite of the
7840 // previous test in order to increase test coverage.
7841 bool err_allowed = false;
7842 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7843 TestDelegate d;
7844 {
7845 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197846 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367847 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337848
[email protected]f7022f32014-08-21 16:32:197849 r->Start();
7850 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337851
[email protected]255620da2013-08-19 13:14:297852 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337853
7854 EXPECT_EQ(1, d.response_started_count());
7855 EXPECT_FALSE(d.received_data_before_response());
7856 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177857 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337858 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197859 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177860 } else {
[email protected]bacff652009-03-31 17:50:337861 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177862 }
[email protected]bacff652009-03-31 17:50:337863 }
7864 }
7865}
[email protected]73e0bba2009-02-19 22:57:097866
davidbena4c9d062015-04-03 22:34:257867// Tests that servers which require a deprecated cipher suite still work.
7868TEST_F(HTTPSRequestTest, CipherFallbackTest) {
vishal.b62985ca92015-04-17 08:45:517869 TestNetLog net_log;
davidbena4c9d062015-04-03 22:34:257870 default_context_.set_net_log(&net_log);
7871
7872 SpawnedTestServer::SSLOptions ssl_options;
7873 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
7874 SpawnedTestServer test_server(
7875 SpawnedTestServer::TYPE_HTTPS, ssl_options,
7876 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7877 ASSERT_TRUE(test_server.Start());
7878
7879 TestDelegate d;
7880 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7881 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7882 r->Start();
7883 EXPECT_TRUE(r->is_pending());
7884
7885 base::RunLoop().Run();
7886
7887 EXPECT_EQ(1, d.response_started_count());
7888 EXPECT_FALSE(d.received_data_before_response());
7889 EXPECT_NE(0, d.bytes_received());
7890 CheckSSLInfo(r->ssl_info());
7891 EXPECT_EQ(test_server.host_port_pair().host(), r->GetSocketAddress().host());
7892 EXPECT_EQ(test_server.host_port_pair().port(), r->GetSocketAddress().port());
7893
7894 // No version downgrade should have been necessary.
7895 EXPECT_FALSE(r->ssl_info().connection_status &
7896 SSL_CONNECTION_VERSION_FALLBACK);
davidben6cacd572015-09-29 22:24:107897 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_2,
davidbena4c9d062015-04-03 22:34:257898 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
7899
mmenke43758e62015-05-04 21:09:467900 TestNetLogEntry::List entries;
davidbena4c9d062015-04-03 22:34:257901 net_log.GetEntries(&entries);
7902 ExpectLogContainsSomewhere(entries, 0, NetLog::TYPE_SSL_CIPHER_FALLBACK,
7903 NetLog::PHASE_NONE);
7904}
7905
[email protected]316c1e5e2012-09-12 15:17:447906// This tests that a load of www.google.com with a certificate error sets
7907// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7908// the interstitial to be fatal.
7909TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227910 SpawnedTestServer::SSLOptions ssl_options(
7911 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7912 SpawnedTestServer test_server(
7913 SpawnedTestServer::TYPE_HTTPS,
7914 ssl_options,
7915 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447916 ASSERT_TRUE(test_server.Start());
7917
7918 // We require that the URL be www.google.com in order to pick up the
7919 // preloaded HSTS entries in the TransportSecurityState. This means that we
7920 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247921 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447922
7923 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247924 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447925 TestURLRequestContext context(true);
7926 context.set_network_delegate(&network_delegate);
7927 context.set_host_resolver(&host_resolver);
7928 TransportSecurityState transport_security_state;
7929 context.set_transport_security_state(&transport_security_state);
7930 context.Init();
7931
7932 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197933 scoped_ptr<URLRequest> r(context.CreateRequest(
7934 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367935 test_server.host_port_pair().port())),
7936 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447937
[email protected]f7022f32014-08-21 16:32:197938 r->Start();
7939 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447940
[email protected]255620da2013-08-19 13:14:297941 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447942
7943 EXPECT_EQ(1, d.response_started_count());
7944 EXPECT_FALSE(d.received_data_before_response());
7945 EXPECT_TRUE(d.have_certificate_errors());
7946 EXPECT_TRUE(d.certificate_errors_are_fatal());
7947}
7948
7949// This tests that cached HTTPS page loads do not cause any updates to the
7950// TransportSecurityState.
7951TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7952 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7953 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227954 SpawnedTestServer::SSLOptions ssl_options(
7955 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7956 SpawnedTestServer test_server(
7957 SpawnedTestServer::TYPE_HTTPS,
7958 ssl_options,
7959 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447960 ASSERT_TRUE(test_server.Start());
7961
[email protected]9e6968d2014-05-07 21:46:267962 // We require that the URL be www.google.com in order to pick up the static
7963 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7964 // that we have to use a MockHostResolver in order to direct www.google.com to
7965 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447966
7967 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247968 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447969 TestURLRequestContext context(true);
7970 context.set_network_delegate(&network_delegate);
7971 context.set_host_resolver(&host_resolver);
7972 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267973
martijnc0d6b622015-06-30 19:14:407974 TransportSecurityState::STSState static_sts_state;
7975 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:267976 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:407977 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:447978 context.set_transport_security_state(&transport_security_state);
7979 context.Init();
7980
martijnc0d6b622015-06-30 19:14:407981 TransportSecurityState::STSState dynamic_sts_state;
7982 TransportSecurityState::PKPState dynamic_pkp_state;
7983 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
7984 &dynamic_sts_state));
7985 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
7986 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:267987
[email protected]316c1e5e2012-09-12 15:17:447988 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197989 scoped_ptr<URLRequest> r(context.CreateRequest(
7990 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367991 test_server.host_port_pair().port())),
7992 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447993
[email protected]f7022f32014-08-21 16:32:197994 r->Start();
7995 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447996
[email protected]255620da2013-08-19 13:14:297997 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447998
7999 EXPECT_EQ(1, d.response_started_count());
8000 EXPECT_FALSE(d.received_data_before_response());
8001 EXPECT_TRUE(d.have_certificate_errors());
8002 EXPECT_TRUE(d.certificate_errors_are_fatal());
8003
[email protected]9e6968d2014-05-07 21:46:268004 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408005 TransportSecurityState::STSState new_static_sts_state;
8006 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268007 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408008 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8009 TransportSecurityState::STSState new_dynamic_sts_state;
8010 TransportSecurityState::PKPState new_dynamic_pkp_state;
8011 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8012 "www.google.com", &new_dynamic_sts_state));
8013 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8014 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268015
martijnc0d6b622015-06-30 19:14:408016 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8017 EXPECT_EQ(new_static_sts_state.include_subdomains,
8018 static_sts_state.include_subdomains);
8019 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8020 static_pkp_state.include_subdomains);
8021 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.spki_hashes,
8022 static_pkp_state.spki_hashes));
8023 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.bad_spki_hashes,
8024 static_pkp_state.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:448025}
8026
[email protected]8ccc69f2012-11-28 19:52:148027// Make sure HSTS preserves a POST request's method and body.
8028TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8029 static const char kData[] = "hello world";
8030
[email protected]ce7d0cbc2013-05-03 18:57:228031 SpawnedTestServer::SSLOptions ssl_options(
8032 SpawnedTestServer::SSLOptions::CERT_OK);
8033 SpawnedTestServer test_server(
8034 SpawnedTestServer::TYPE_HTTPS,
8035 ssl_options,
8036 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148037 ASSERT_TRUE(test_server.Start());
8038
8039
8040 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8041 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:228042 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
8043 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148044 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148045
8046 // Force https for www.somewhere.com.
8047 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208048 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8049 bool include_subdomains = false;
8050 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8051 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148052
8053 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8054
8055 TestURLRequestContext context(true);
8056 context.set_host_resolver(&host_resolver);
8057 context.set_transport_security_state(&transport_security_state);
8058 context.set_network_delegate(&network_delegate);
8059 context.Init();
8060
8061 TestDelegate d;
8062 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8063 // cause a certificate error. Ignore the error.
8064 d.set_allow_certificate_errors(true);
8065
[email protected]f7022f32014-08-21 16:32:198066 scoped_ptr<URLRequest> req(context.CreateRequest(
8067 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368068 test_server.host_port_pair().port())),
8069 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198070 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078071 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148072
[email protected]f7022f32014-08-21 16:32:198073 req->Start();
[email protected]255620da2013-08-19 13:14:298074 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148075
[email protected]f7022f32014-08-21 16:32:198076 EXPECT_EQ("https", req->url().scheme());
8077 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148078 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408079
8080 LoadTimingInfo load_timing_info;
8081 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8082 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8083 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148084}
8085
rob4e0be1f2014-09-11 23:40:228086// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8087TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8088 static const char kOriginHeaderValue[] = "http://www.example.com";
8089
8090 SpawnedTestServer::SSLOptions ssl_options(
8091 SpawnedTestServer::SSLOptions::CERT_OK);
8092 SpawnedTestServer test_server(
8093 SpawnedTestServer::TYPE_HTTPS,
8094 ssl_options,
8095 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8096 ASSERT_TRUE(test_server.Start());
8097
8098 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8099 // address, so a MockHostResolver is needed to redirect example.net to the
8100 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
8101 MockHostResolver host_resolver;
8102
8103 TransportSecurityState transport_security_state;
8104 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8105 bool include_subdomains = false;
8106 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8107
8108 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8109
8110 MockCertVerifier cert_verifier;
8111 cert_verifier.set_default_result(OK);
8112
8113 TestURLRequestContext context(true);
8114 context.set_host_resolver(&host_resolver);
8115 context.set_transport_security_state(&transport_security_state);
8116 context.set_network_delegate(&network_delegate);
8117 context.set_cert_verifier(&cert_verifier);
8118 context.Init();
8119
8120 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8121 test_server.host_port_pair().port()));
8122 url::Replacements<char> replacements;
8123 const char kNewScheme[] = "https";
8124 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8125 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8126
8127 TestDelegate d;
8128 // Quit on redirect to allow response header inspection upon redirect.
8129 d.set_quit_on_redirect(true);
8130
davidben151423e2015-03-23 18:48:368131 scoped_ptr<URLRequest> req(
8132 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228133 // Set Origin header to simulate a cross-origin request.
8134 HttpRequestHeaders request_headers;
8135 request_headers.SetHeader("Origin", kOriginHeaderValue);
8136 req->SetExtraRequestHeaders(request_headers);
8137
8138 req->Start();
8139 base::RunLoop().Run();
8140
8141 EXPECT_EQ(1, d.received_redirect_count());
8142
8143 const HttpResponseHeaders* headers = req->response_headers();
8144 std::string redirect_location;
8145 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8146 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8147
8148 std::string received_cors_header;
8149 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8150 &received_cors_header));
8151 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8152}
8153
Adam Ricecb76ac62015-02-20 05:33:258154// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
8155// are performed in net/websockets/websocket_end_to_end_test.cc.
8156TEST(WebSocketURLRequestTest, HSTSApplied) {
8157 TestNetworkDelegate network_delegate;
8158 TransportSecurityState transport_security_state;
8159 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8160 bool include_subdomains = false;
8161 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8162 TestURLRequestContext context(true);
8163 context.set_transport_security_state(&transport_security_state);
8164 context.set_network_delegate(&network_delegate);
8165 context.Init();
8166 GURL ws_url("ws://example.net/echo");
8167 TestDelegate delegate;
8168 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:368169 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:258170 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
8171 EXPECT_TRUE(ws_url.SchemeIs("wss"));
8172}
8173
[email protected]316c1e5e2012-09-12 15:17:448174namespace {
8175
8176class SSLClientAuthTestDelegate : public TestDelegate {
8177 public:
8178 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8179 }
dchengb03027d2014-10-21 12:00:208180 void OnCertificateRequested(URLRequest* request,
8181 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448182 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178183 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448184 }
8185 int on_certificate_requested_count() {
8186 return on_certificate_requested_count_;
8187 }
8188 private:
8189 int on_certificate_requested_count_;
8190};
8191
8192} // namespace
8193
8194// TODO(davidben): Test the rest of the code. Specifically,
8195// - Filtering which certificates to select.
8196// - Sending a certificate back.
8197// - Getting a certificate request in an SSL renegotiation sending the
8198// HTTP request.
8199TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:228200 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448201 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:228202 SpawnedTestServer test_server(
8203 SpawnedTestServer::TYPE_HTTPS,
8204 ssl_options,
8205 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448206 ASSERT_TRUE(test_server.Start());
8207
8208 SSLClientAuthTestDelegate d;
8209 {
[email protected]f7022f32014-08-21 16:32:198210 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368211 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448212
[email protected]f7022f32014-08-21 16:32:198213 r->Start();
8214 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448215
[email protected]255620da2013-08-19 13:14:298216 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448217
8218 EXPECT_EQ(1, d.on_certificate_requested_count());
8219 EXPECT_FALSE(d.received_data_before_response());
8220 EXPECT_EQ(0, d.bytes_received());
8221
8222 // Send no certificate.
8223 // TODO(davidben): Get temporary client cert import (with keys) working on
8224 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:198225 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:448226
[email protected]255620da2013-08-19 13:14:298227 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448228
8229 EXPECT_EQ(1, d.response_started_count());
8230 EXPECT_FALSE(d.received_data_before_response());
8231 EXPECT_NE(0, d.bytes_received());
8232 }
8233}
8234
8235TEST_F(HTTPSRequestTest, ResumeTest) {
8236 // Test that we attempt a session resume when making two connections to the
8237 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228238 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448239 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228240 SpawnedTestServer test_server(
8241 SpawnedTestServer::TYPE_HTTPS,
8242 ssl_options,
8243 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448244 ASSERT_TRUE(test_server.Start());
8245
8246 SSLClientSocket::ClearSessionCache();
8247
8248 {
8249 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198250 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368251 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448252
[email protected]f7022f32014-08-21 16:32:198253 r->Start();
8254 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448255
[email protected]255620da2013-08-19 13:14:298256 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448257
8258 EXPECT_EQ(1, d.response_started_count());
8259 }
8260
8261 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8262 CloseAllConnections();
8263
8264 {
8265 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198266 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368267 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448268
[email protected]f7022f32014-08-21 16:32:198269 r->Start();
8270 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448271
[email protected]255620da2013-08-19 13:14:298272 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448273
8274 // The response will look like;
8275 // insert abc
8276 // lookup abc
8277 // insert xyz
8278 //
8279 // With a newline at the end which makes the split think that there are
8280 // four lines.
8281
8282 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298283 std::vector<std::string> lines = base::SplitString(
8284 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448285 ASSERT_EQ(4u, lines.size()) << d.data_received();
8286
8287 std::string session_id;
8288
8289 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298290 std::vector<std::string> parts = base::SplitString(
8291 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448292 ASSERT_EQ(2u, parts.size());
8293 if (i == 0) {
8294 EXPECT_EQ("insert", parts[0]);
8295 session_id = parts[1];
8296 } else {
8297 EXPECT_EQ("lookup", parts[0]);
8298 EXPECT_EQ(session_id, parts[1]);
8299 }
8300 }
8301 }
8302}
8303
Adam Langley32352ad2014-10-14 22:31:008304// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8305// the result of fetching "ssl-session-cache" from the test server, indicates
8306// that exactly two different sessions were inserted, with no lookups etc.
8307static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298308 std::vector<std::string> lines = base::SplitString(
8309 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008310 ASSERT_EQ(3u, lines.size()) << session_info;
8311
8312 std::string session_id;
8313 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298314 std::vector<std::string> parts = base::SplitString(
8315 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008316 ASSERT_EQ(2u, parts.size());
8317 EXPECT_EQ("insert", parts[0]);
8318 if (i == 0) {
8319 session_id = parts[1];
8320 } else {
8321 EXPECT_NE(session_id, parts[1]);
8322 }
8323 }
8324}
8325
[email protected]316c1e5e2012-09-12 15:17:448326TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8327 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8328 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228329 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448330 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228331 SpawnedTestServer test_server(
8332 SpawnedTestServer::TYPE_HTTPS,
8333 ssl_options,
8334 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448335 ASSERT_TRUE(test_server.Start());
8336
8337 SSLClientSocket::ClearSessionCache();
8338
8339 {
8340 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198341 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368342 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448343
[email protected]f7022f32014-08-21 16:32:198344 r->Start();
8345 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448346
[email protected]255620da2013-08-19 13:14:298347 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448348
8349 EXPECT_EQ(1, d.response_started_count());
8350 }
8351
8352 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8353 HttpNetworkSession::Params params;
8354 params.host_resolver = default_context_.host_resolver();
8355 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118356 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:448357 params.proxy_service = default_context_.proxy_service();
8358 params.ssl_config_service = default_context_.ssl_config_service();
8359 params.http_auth_handler_factory =
8360 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:418361 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:448362 params.http_server_properties = default_context_.http_server_properties();
8363 params.ssl_session_cache_shard = "alternate";
8364
mmenkee65e7af2015-10-13 17:16:428365 HttpNetworkSession network_session(params);
[email protected]cba24642014-08-15 20:49:598366 scoped_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428367 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448368
8369 default_context_.set_http_transaction_factory(cache.get());
8370
8371 {
8372 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198373 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368374 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448375
[email protected]f7022f32014-08-21 16:32:198376 r->Start();
8377 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448378
[email protected]255620da2013-08-19 13:14:298379 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448380
8381 // The response will look like;
8382 // insert abc
8383 // insert xyz
8384 //
8385 // With a newline at the end which makes the split think that there are
8386 // three lines.
8387
8388 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008389 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448390 }
8391}
8392
davidben8ecc3072014-09-03 23:19:098393#if defined(OS_WIN)
8394
8395namespace {
8396
8397bool IsECDSACipherSuite(uint16_t cipher_suite) {
8398 const char* key_exchange;
8399 const char* cipher;
8400 const char* mac;
8401 bool is_aead;
8402 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
8403 return std::string(key_exchange).find("ECDSA") != std::string::npos;
8404}
8405
8406} // namespace
8407
8408// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
8409// verified.
davidben9399c952014-10-07 04:09:118410TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:098411 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
8412 LOG(INFO) << "Skipping test on this version.";
8413 return;
8414 }
8415
8416 SpawnedTestServer test_server(
8417 SpawnedTestServer::TYPE_HTTPS,
8418 SpawnedTestServer::kLocalhost,
8419 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8420 ASSERT_TRUE(test_server.Start());
8421
8422 TestDelegate d;
8423 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368424 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:098425 r->Start();
8426 EXPECT_TRUE(r->is_pending());
8427
8428 base::RunLoop().Run();
8429
8430 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298431 std::vector<std::string> lines = base::SplitString(
8432 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
davidben8ecc3072014-09-03 23:19:098433
8434 for (size_t i = 0; i < lines.size(); i++) {
8435 int cipher_suite;
8436 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
8437 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
8438 << "ClientHello advertised " << cipher_suite;
8439 }
8440}
8441
8442#endif // OS_WIN
8443
Adam Langley32352ad2014-10-14 22:31:008444class TestSSLConfigService : public SSLConfigService {
8445 public:
8446 TestSSLConfigService(bool ev_enabled,
8447 bool online_rev_checking,
8448 bool rev_checking_required_local_anchors)
8449 : ev_enabled_(ev_enabled),
8450 online_rev_checking_(online_rev_checking),
8451 rev_checking_required_local_anchors_(
8452 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:028453 min_version_(kDefaultSSLVersionMin),
8454 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
8455
8456 void set_min_version(uint16 version) {
8457 min_version_ = version;
8458 }
Adam Langley32352ad2014-10-14 22:31:008459
8460 void set_fallback_min_version(uint16 version) {
8461 fallback_min_version_ = version;
8462 }
8463
8464 // SSLConfigService:
dchengb03027d2014-10-21 12:00:208465 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:008466 *config = SSLConfig();
8467 config->rev_checking_enabled = online_rev_checking_;
8468 config->verify_ev_cert = ev_enabled_;
8469 config->rev_checking_required_local_anchors =
8470 rev_checking_required_local_anchors_;
8471 if (fallback_min_version_) {
8472 config->version_fallback_min = fallback_min_version_;
8473 }
Adam Langleyac6f24b42014-10-31 20:24:028474 if (min_version_) {
8475 config->version_min = min_version_;
8476 }
Adam Langley32352ad2014-10-14 22:31:008477 }
8478
8479 protected:
dchengb03027d2014-10-21 12:00:208480 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:008481
8482 private:
8483 const bool ev_enabled_;
8484 const bool online_rev_checking_;
8485 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:028486 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:008487 uint16 fallback_min_version_;
8488};
8489
8490class FallbackTestURLRequestContext : public TestURLRequestContext {
8491 public:
8492 explicit FallbackTestURLRequestContext(bool delay_initialization)
8493 : TestURLRequestContext(delay_initialization) {}
8494
8495 void set_fallback_min_version(uint16 version) {
8496 TestSSLConfigService *ssl_config_service =
8497 new TestSSLConfigService(true /* check for EV */,
8498 false /* online revocation checking */,
8499 false /* require rev. checking for local
8500 anchors */);
8501 ssl_config_service->set_fallback_min_version(version);
8502 set_ssl_config_service(ssl_config_service);
8503 }
8504};
8505
[email protected]48d2b7c52014-06-27 01:16:558506class HTTPSFallbackTest : public testing::Test {
8507 public:
Adam Langley32352ad2014-10-14 22:31:008508 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298509 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558510
8511 protected:
8512 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8513 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008514 context_.Init();
8515 delegate_.set_allow_certificate_errors(true);
8516
[email protected]48d2b7c52014-06-27 01:16:558517 SpawnedTestServer test_server(
8518 SpawnedTestServer::TYPE_HTTPS,
8519 ssl_options,
8520 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8521 ASSERT_TRUE(test_server.Start());
8522
davidben151423e2015-03-23 18:48:368523 request_ = context_.CreateRequest(test_server.GetURL(std::string()),
8524 DEFAULT_PRIORITY, &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558525 request_->Start();
8526
8527 base::RunLoop().Run();
8528 }
8529
Adam Langley32352ad2014-10-14 22:31:008530 void set_fallback_min_version(uint16 version) {
8531 context_.set_fallback_min_version(version);
8532 }
8533
[email protected]48d2b7c52014-06-27 01:16:558534 void ExpectConnection(int version) {
8535 EXPECT_EQ(1, delegate_.response_started_count());
8536 EXPECT_NE(0, delegate_.bytes_received());
8537 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8538 request_->ssl_info().connection_status));
8539 EXPECT_TRUE(request_->ssl_info().connection_status &
8540 SSL_CONNECTION_VERSION_FALLBACK);
8541 }
8542
8543 void ExpectFailure(int error) {
8544 EXPECT_EQ(1, delegate_.response_started_count());
8545 EXPECT_FALSE(request_->status().is_success());
8546 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8547 EXPECT_EQ(error, request_->status().error());
8548 }
8549
8550 private:
8551 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008552 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558553 scoped_ptr<URLRequest> request_;
8554};
8555
davidbenb127ca82015-06-15 19:05:428556// Tests the TLS 1.0 fallback doesn't happen.
8557TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558558 SpawnedTestServer::SSLOptions ssl_options(
8559 SpawnedTestServer::SSLOptions::CERT_OK);
8560 ssl_options.tls_intolerant =
8561 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8562
8563 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428564 ExpectFailure(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION);
8565}
8566
8567// Tests the TLS 1.1 fallback.
8568TEST_F(HTTPSFallbackTest, TLSv1_1Fallback) {
davidbenb127ca82015-06-15 19:05:428569 SpawnedTestServer::SSLOptions ssl_options(
8570 SpawnedTestServer::SSLOptions::CERT_OK);
8571 ssl_options.tls_intolerant =
8572 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8573
8574 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8575 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
8576}
8577
8578// Tests that the TLS 1.1 fallback triggers on closed connections.
8579TEST_F(HTTPSFallbackTest, TLSv1_1FallbackClosed) {
davidbenb127ca82015-06-15 19:05:428580 SpawnedTestServer::SSLOptions ssl_options(
8581 SpawnedTestServer::SSLOptions::CERT_OK);
8582 ssl_options.tls_intolerant =
8583 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8584 ssl_options.tls_intolerance_type =
8585 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8586
8587 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8588 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558589}
8590
8591// This test is disabled on Android because the remote test server doesn't cause
8592// a TCP reset.
8593#if !defined(OS_ANDROID)
davidbenb127ca82015-06-15 19:05:428594// Tests fallback to TLS 1.1 on connection reset.
8595TEST_F(HTTPSFallbackTest, TLSv1_1FallbackReset) {
[email protected]48d2b7c52014-06-27 01:16:558596 SpawnedTestServer::SSLOptions ssl_options(
8597 SpawnedTestServer::SSLOptions::CERT_OK);
8598 ssl_options.tls_intolerant =
davidbenb127ca82015-06-15 19:05:428599 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
[email protected]48d2b7c52014-06-27 01:16:558600 ssl_options.tls_intolerance_type =
8601 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8602
8603 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428604 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558605}
8606#endif // !OS_ANDROID
8607
[email protected]12833302014-07-02 01:57:318608// Tests that we don't fallback on handshake failure with servers that implement
8609// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558610TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558611 SpawnedTestServer::SSLOptions ssl_options(
8612 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438613 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558614 // a version fallback.
8615 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438616 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558617 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8618 // connections are rejected.
8619 ssl_options.fallback_scsv_enabled = true;
8620
8621 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8622
8623 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8624 // intolerance. If the fallback SCSV is processed when the original error
8625 // that caused the fallback should be returned, which should be
8626 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8627 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8628}
8629
[email protected]12833302014-07-02 01:57:318630// Tests that we don't fallback on connection closed with servers that implement
8631// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318632TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318633 SpawnedTestServer::SSLOptions ssl_options(
8634 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438635 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318636 // a version fallback.
8637 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438638 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318639 ssl_options.tls_intolerance_type =
8640 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8641 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8642 // connections are rejected.
8643 ssl_options.fallback_scsv_enabled = true;
8644
8645 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8646
8647 // The original error should be replayed on rejected fallback.
8648 ExpectFailure(ERR_CONNECTION_CLOSED);
8649}
8650
davidbenb937d6c2015-05-14 04:53:428651// Test that fallback probe connections don't cause sessions to be cached.
8652TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008653 SpawnedTestServer::SSLOptions ssl_options(
8654 SpawnedTestServer::SSLOptions::CERT_OK);
8655 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428656 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008657 ssl_options.tls_intolerance_type =
8658 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8659 ssl_options.record_resume = true;
8660
8661 SpawnedTestServer test_server(
8662 SpawnedTestServer::TYPE_HTTPS,
8663 ssl_options,
8664 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8665 ASSERT_TRUE(test_server.Start());
8666
8667 SSLClientSocket::ClearSessionCache();
8668
davidbenb937d6c2015-05-14 04:53:428669 // Make a connection that does a probe fallback to TLSv1 but fails because
8670 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008671 // be inserted locally.
8672 {
8673 TestDelegate delegate;
8674 FallbackTestURLRequestContext context(true);
8675
davidbenb937d6c2015-05-14 04:53:428676 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008677 context.Init();
8678 scoped_ptr<URLRequest> request(context.CreateRequest(
davidben151423e2015-03-23 18:48:368679 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008680 request->Start();
8681
8682 base::RunLoop().Run();
8683
8684 EXPECT_EQ(1, delegate.response_started_count());
8685 EXPECT_FALSE(request->status().is_success());
8686 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8687 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8688 request->status().error());
8689 }
8690
davidbenb937d6c2015-05-14 04:53:428691 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008692 {
8693 TestDelegate delegate;
8694 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428695 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008696
8697 context.Init();
davidben151423e2015-03-23 18:48:368698 scoped_ptr<URLRequest> request(context.CreateRequest(
8699 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008700 request->Start();
8701
8702 base::RunLoop().Run();
8703
8704 EXPECT_EQ(1, delegate.response_started_count());
8705 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428706 EXPECT_EQ(
8707 SSL_CONNECTION_VERSION_TLS1,
8708 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008709 EXPECT_TRUE(request->ssl_info().connection_status &
8710 SSL_CONNECTION_VERSION_FALLBACK);
8711
8712 std::vector<std::string> lines;
8713 // If no sessions were cached then the server should have seen two sessions
8714 // inserted with no lookups.
8715 AssertTwoDistinctSessionsInserted(delegate.data_received());
8716 }
8717}
8718
[email protected]a8fed1742013-12-27 02:14:248719class HTTPSSessionTest : public testing::Test {
8720 public:
8721 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598722 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248723
8724 default_context_.set_network_delegate(&default_network_delegate_);
8725 default_context_.set_cert_verifier(&cert_verifier_);
8726 default_context_.Init();
8727 }
dcheng67be2b1f2014-10-27 21:47:298728 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248729
8730 protected:
8731 MockCertVerifier cert_verifier_;
8732 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8733 TestURLRequestContext default_context_;
8734};
8735
8736// Tests that session resumption is not attempted if an invalid certificate
8737// is presented.
8738TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8739 SpawnedTestServer::SSLOptions ssl_options;
8740 ssl_options.record_resume = true;
8741 SpawnedTestServer test_server(
8742 SpawnedTestServer::TYPE_HTTPS,
8743 ssl_options,
8744 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8745 ASSERT_TRUE(test_server.Start());
8746
8747 SSLClientSocket::ClearSessionCache();
8748
8749 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598750 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248751 {
8752 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198753 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368754 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248755
[email protected]f7022f32014-08-21 16:32:198756 r->Start();
8757 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248758
8759 base::RunLoop().Run();
8760
8761 EXPECT_EQ(1, d.response_started_count());
8762 }
8763
8764 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8765 CloseAllConnections();
8766
8767 // Now change the certificate to be acceptable (so that the response is
8768 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598769 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248770 {
8771 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198772 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368773 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248774
[email protected]f7022f32014-08-21 16:32:198775 r->Start();
8776 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248777
8778 base::RunLoop().Run();
8779
8780 // The response will look like;
8781 // insert abc
8782 // insert xyz
8783 //
8784 // With a newline at the end which makes the split think that there are
8785 // three lines.
8786 //
8787 // If a session was presented (eg: a bug), then the response would look
8788 // like;
8789 // insert abc
8790 // lookup abc
8791 // insert xyz
8792
8793 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008794 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248795 }
8796}
8797
[email protected]dffe8242012-03-20 15:14:278798// This the fingerprint of the "Testing CA" certificate used by the testserver.
8799// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268800static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278801 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8802 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8803
[email protected]51523f52013-07-31 21:57:288804// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8805// testserver.
8806static const SHA256HashValue kOCSPTestCertSPKI = { {
8807 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8808 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8809 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8810 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8811} };
8812
[email protected]dffe8242012-03-20 15:14:278813// This is the policy OID contained in the certificates that testserver
8814// generates.
8815static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8816
8817class HTTPSOCSPTest : public HTTPSRequestTest {
8818 public:
8819 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098820 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088821 ev_test_policy_(
8822 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8823 kOCSPTestCertFingerprint,
8824 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028825 }
8826
dcheng67be2b1f2014-10-27 21:47:298827 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098828 SetupContext(&context_);
8829 context_.Init();
[email protected]dffe8242012-03-20 15:14:278830
[email protected]cba24642014-08-15 20:49:598831 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208832 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428833 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508834 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278835
davidben71f35ff2015-04-17 20:54:488836#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098837 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278838 EnsureNSSHttpIOInit();
8839#endif
8840 }
8841
[email protected]ce7d0cbc2013-05-03 18:57:228842 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278843 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538844 // We always overwrite out_cert_status.
8845 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228846 SpawnedTestServer test_server(
8847 SpawnedTestServer::TYPE_HTTPS,
8848 ssl_options,
8849 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278850 ASSERT_TRUE(test_server.Start());
8851
8852 TestDelegate d;
8853 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:198854 scoped_ptr<URLRequest> r(context_.CreateRequest(
davidben151423e2015-03-23 18:48:368855 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198856 r->Start();
[email protected]dffe8242012-03-20 15:14:278857
[email protected]255620da2013-08-19 13:14:298858 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278859
8860 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198861 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278862 }
8863
dcheng67be2b1f2014-10-27 21:47:298864 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488865#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278866 ShutdownNSSHttpIO();
8867#endif
8868 }
8869
[email protected]a13234c2012-03-20 21:45:028870 protected:
8871 // SetupContext configures the URLRequestContext that will be used for making
8872 // connetions to testserver. This can be overridden in test subclasses for
8873 // different behaviour.
8874 virtual void SetupContext(URLRequestContext* context) {
8875 context->set_ssl_config_service(
8876 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208877 true /* online revocation checking */,
8878 false /* require rev. checking for local
8879 anchors */));
[email protected]a13234c2012-03-20 21:45:028880 }
8881
[email protected]dffe8242012-03-20 15:14:278882 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098883 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088884 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278885};
8886
[email protected]a13234c2012-03-20 21:45:028887static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018888#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028889 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8890 // have that ability on other platforms.
8891 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8892#else
8893 return 0;
8894#endif
8895}
8896
[email protected]3a86a712013-07-30 07:16:208897// SystemSupportsHardFailRevocationChecking returns true iff the current
8898// operating system supports revocation checking and can distinguish between
8899// situations where a given certificate lacks any revocation information (eg:
8900// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8901// revocation information cannot be obtained (eg: the CRL was unreachable).
8902// If it does not, then tests which rely on 'hard fail' behaviour should be
8903// skipped.
8904static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:488905#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:208906 return true;
8907#else
8908 return false;
8909#endif
8910}
8911
[email protected]a13234c2012-03-20 21:45:028912// SystemUsesChromiumEVMetadata returns true iff the current operating system
8913// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8914// several tests are effected because our testing EV certificate won't be
8915// recognised as EV.
8916static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328917#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578918 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8919 return false;
[email protected]e1b2d732014-03-28 16:20:328920#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8921 // On OS X and Android, we use the system to tell us whether a certificate is
8922 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018923 return false;
8924#else
8925 return true;
8926#endif
8927}
8928
[email protected]b6f2de32012-08-17 04:35:088929static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008930#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578931 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8932 return false;
8933#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028934 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8935#elif defined(OS_ANDROID)
8936 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8937 return false;
8938#else
8939 return true;
8940#endif
8941}
8942
davidbend1fb2f12014-11-08 02:51:008943static bool SystemSupportsOCSPStapling() {
davidben74b12ef02015-07-17 16:47:178944#if defined(USE_NSS_CERTS) || defined(OS_IOS)
davidbend1fb2f12014-11-08 02:51:008945 return true;
8946#elif defined(OS_WIN)
8947 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8948#else
8949 return false;
8950#endif
8951}
8952
[email protected]dffe8242012-03-20 15:14:278953TEST_F(HTTPSOCSPTest, Valid) {
8954 if (!SystemSupportsOCSP()) {
8955 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8956 return;
8957 }
8958
[email protected]ce7d0cbc2013-05-03 18:57:228959 SpawnedTestServer::SSLOptions ssl_options(
8960 SpawnedTestServer::SSLOptions::CERT_AUTO);
8961 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278962
[email protected]924e9f92012-12-16 22:00:538963 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128964 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278965
8966 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8967
[email protected]a13234c2012-03-20 21:45:028968 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8969 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278970
8971 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8972}
8973
8974TEST_F(HTTPSOCSPTest, Revoked) {
8975 if (!SystemSupportsOCSP()) {
8976 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8977 return;
8978 }
8979
[email protected]ce7d0cbc2013-05-03 18:57:228980 SpawnedTestServer::SSLOptions ssl_options(
8981 SpawnedTestServer::SSLOptions::CERT_AUTO);
8982 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278983
8984 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128985 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278986
[email protected]a592c0432012-12-01 18:10:298987#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278988 // Doesn't pass on OS X yet for reasons that need to be investigated.
8989 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8990#endif
8991 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8992 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8993}
8994
8995TEST_F(HTTPSOCSPTest, Invalid) {
8996 if (!SystemSupportsOCSP()) {
8997 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8998 return;
8999 }
9000
[email protected]ce7d0cbc2013-05-03 18:57:229001 SpawnedTestServer::SSLOptions ssl_options(
9002 SpawnedTestServer::SSLOptions::CERT_AUTO);
9003 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:279004
[email protected]924e9f92012-12-16 22:00:539005 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129006 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279007
[email protected]a13234c2012-03-20 21:45:029008 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:279009 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279010
9011 // Without a positive OCSP response, we shouldn't show the EV status.
9012 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9013 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9014}
[email protected]a13234c2012-03-20 21:45:029015
davidbend1fb2f12014-11-08 02:51:009016TEST_F(HTTPSOCSPTest, ValidStapled) {
9017 if (!SystemSupportsOCSPStapling()) {
9018 LOG(WARNING)
9019 << "Skipping test because system doesn't support OCSP stapling";
9020 return;
9021 }
9022
9023 SpawnedTestServer::SSLOptions ssl_options(
9024 SpawnedTestServer::SSLOptions::CERT_AUTO);
9025 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9026 ssl_options.staple_ocsp_response = true;
9027 ssl_options.ocsp_server_unavailable = true;
9028
9029 CertStatus cert_status;
9030 DoConnection(ssl_options, &cert_status);
9031
9032 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9033
9034 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9035 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9036
9037 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9038}
9039
davidben6c3191b2014-11-21 22:38:049040// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489041#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049042#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9043#else
9044#define MAYBE_RevokedStapled RevokedStapled
9045#endif
9046TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
davidbend1fb2f12014-11-08 02:51:009047 if (!SystemSupportsOCSPStapling()) {
9048 LOG(WARNING)
9049 << "Skipping test because system doesn't support OCSP stapling";
9050 return;
9051 }
9052
9053 SpawnedTestServer::SSLOptions ssl_options(
9054 SpawnedTestServer::SSLOptions::CERT_AUTO);
9055 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9056 ssl_options.staple_ocsp_response = true;
9057 ssl_options.ocsp_server_unavailable = true;
9058
9059 CertStatus cert_status;
9060 DoConnection(ssl_options, &cert_status);
9061
9062 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9063 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9064 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9065}
9066
[email protected]3a86a712013-07-30 07:16:209067class HTTPSHardFailTest : public HTTPSOCSPTest {
9068 protected:
dchengb03027d2014-10-21 12:00:209069 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:209070 context->set_ssl_config_service(
9071 new TestSSLConfigService(false /* check for EV */,
9072 false /* online revocation checking */,
9073 true /* require rev. checking for local
9074 anchors */));
9075 }
9076};
9077
[email protected]3a86a712013-07-30 07:16:209078TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
9079 if (!SystemSupportsOCSP()) {
9080 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9081 return;
9082 }
9083
9084 if (!SystemSupportsHardFailRevocationChecking()) {
9085 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
9086 << "revocation checking";
9087 return;
9088 }
9089
9090 SpawnedTestServer::SSLOptions ssl_options(
9091 SpawnedTestServer::SSLOptions::CERT_AUTO);
9092 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9093
9094 CertStatus cert_status;
9095 DoConnection(ssl_options, &cert_status);
9096
9097 EXPECT_EQ(CERT_STATUS_REVOKED,
9098 cert_status & CERT_STATUS_REVOKED);
9099
9100 // Without a positive OCSP response, we shouldn't show the EV status.
9101 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9102}
9103
[email protected]a13234c2012-03-20 21:45:029104class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
9105 protected:
dchengb03027d2014-10-21 12:00:209106 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:029107 context->set_ssl_config_service(
9108 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:209109 false /* online revocation checking */,
9110 false /* require rev. checking for local
9111 anchors */));
[email protected]a13234c2012-03-20 21:45:029112 }
9113};
9114
9115TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
9116 if (!SystemSupportsOCSP()) {
9117 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9118 return;
9119 }
9120
[email protected]ce7d0cbc2013-05-03 18:57:229121 SpawnedTestServer::SSLOptions ssl_options(
9122 SpawnedTestServer::SSLOptions::CERT_AUTO);
9123 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029124 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9125
[email protected]924e9f92012-12-16 22:00:539126 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129127 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029128
9129 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9130 cert_status & CERT_STATUS_ALL_ERRORS);
9131
9132 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089133 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9134 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029135}
9136
[email protected]be0fff62013-08-29 23:37:489137TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
9138 if (!SystemSupportsOCSP()) {
9139 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9140 return;
9141 }
9142
9143 SpawnedTestServer::SSLOptions ssl_options(
9144 SpawnedTestServer::SSLOptions::CERT_AUTO);
9145 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9146 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9147
9148 CertStatus cert_status;
9149 DoConnection(ssl_options, &cert_status);
9150
9151 // Currently only works for Windows. When using NSS or OS X, it's not
9152 // possible to determine whether the check failed because of actual
9153 // revocation or because there was an OCSP failure.
9154#if defined(OS_WIN)
9155 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9156#else
9157 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9158#endif
9159
9160 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9161 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9162 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9163}
9164
[email protected]a13234c2012-03-20 21:45:029165TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
9166 if (!SystemSupportsOCSP()) {
9167 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9168 return;
9169 }
9170
[email protected]ce7d0cbc2013-05-03 18:57:229171 SpawnedTestServer::SSLOptions ssl_options(
9172 SpawnedTestServer::SSLOptions::CERT_AUTO);
9173 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:029174 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9175
9176 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129177 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029178
9179 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9180
9181 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9182 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:089183 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9184 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029185}
9186
9187TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
9188 if (!SystemSupportsOCSP()) {
9189 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9190 return;
9191 }
9192
[email protected]ce7d0cbc2013-05-03 18:57:229193 SpawnedTestServer::SSLOptions ssl_options(
9194 SpawnedTestServer::SSLOptions::CERT_AUTO);
9195 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029196 SSLConfigService::SetCRLSet(
9197 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9198
9199 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129200 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029201
9202 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9203 cert_status & CERT_STATUS_ALL_ERRORS);
9204
9205 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089206 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9207 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029208}
9209
[email protected]51523f52013-07-31 21:57:289210TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9211 if (!SystemSupportsOCSP()) {
9212 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9213 return;
9214 }
9215
9216 SpawnedTestServer::SSLOptions ssl_options(
9217 SpawnedTestServer::SSLOptions::CERT_AUTO);
9218 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9219 SSLConfigService::SetCRLSet(
9220 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9221 false, &kOCSPTestCertSPKI, "")));
9222
9223 CertStatus cert_status;
9224 DoConnection(ssl_options, &cert_status);
9225
9226 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9227 // revocation check for EV.
9228 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9229 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9230 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9231 EXPECT_FALSE(
9232 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9233}
9234
9235TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9236 if (!SystemSupportsOCSP()) {
9237 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9238 return;
9239 }
9240
[email protected]ce7d0cbc2013-05-03 18:57:229241 SpawnedTestServer::SSLOptions ssl_options(
9242 SpawnedTestServer::SSLOptions::CERT_AUTO);
9243 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029244 SSLConfigService::SetCRLSet(
9245 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9246
[email protected]51523f52013-07-31 21:57:289247 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129248 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029249
[email protected]51523f52013-07-31 21:57:289250 // Even with a fresh CRLSet, we should still do online revocation checks when
9251 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9252 // test.
9253 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9254 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029255
[email protected]51523f52013-07-31 21:57:289256 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029257 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289258 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029259}
9260
[email protected]b6f2de32012-08-17 04:35:089261TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9262 // Test that when EV verification is requested, but online revocation
9263 // checking is disabled, and the leaf certificate is not in fact EV, that
9264 // no revocation checking actually happens.
9265 if (!SystemSupportsOCSP()) {
9266 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9267 return;
9268 }
9269
9270 // Unmark the certificate's OID as EV, which should disable revocation
9271 // checking (as per the user preference)
9272 ev_test_policy_.reset();
9273
[email protected]ce7d0cbc2013-05-03 18:57:229274 SpawnedTestServer::SSLOptions ssl_options(
9275 SpawnedTestServer::SSLOptions::CERT_AUTO);
9276 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089277 SSLConfigService::SetCRLSet(
9278 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9279
9280 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129281 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:089282
9283 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9284
9285 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9286 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9287}
9288
[email protected]a13234c2012-03-20 21:45:029289class HTTPSCRLSetTest : public HTTPSOCSPTest {
9290 protected:
dchengb03027d2014-10-21 12:00:209291 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:029292 context->set_ssl_config_service(
9293 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:209294 false /* online revocation checking */,
9295 false /* require rev. checking for local
9296 anchors */));
[email protected]a13234c2012-03-20 21:45:029297 }
9298};
9299
9300TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229301 SpawnedTestServer::SSLOptions ssl_options(
9302 SpawnedTestServer::SSLOptions::CERT_AUTO);
9303 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029304 SSLConfigService::SetCRLSet(
9305 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9306
[email protected]924e9f92012-12-16 22:00:539307 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129308 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029309
9310 // If we're not trying EV verification then, even if the CRLSet has expired,
9311 // we don't fall back to online revocation checks.
9312 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9313 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9314 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9315}
[email protected]51523f52013-07-31 21:57:289316
9317TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309318#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289319 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9320 return;
9321#endif
9322
9323 SpawnedTestServer::SSLOptions ssl_options(
9324 SpawnedTestServer::SSLOptions::CERT_AUTO);
9325 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9326 ssl_options.cert_serial = 10;
9327 SSLConfigService::SetCRLSet(
9328 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9329 false, &kOCSPTestCertSPKI, "\x0a")));
9330
9331 CertStatus cert_status = 0;
9332 DoConnection(ssl_options, &cert_status);
9333
9334 // If the certificate is recorded as revoked in the CRLSet, that should be
9335 // reflected without online revocation checking.
9336 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9337 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9338 EXPECT_FALSE(
9339 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9340}
[email protected]316c1e5e2012-09-12 15:17:449341#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279342
mmenke9f2ec60c2015-06-01 20:59:479343#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9344// These tests aren't passing on Android. Either the RemoteTestServer isn't
9345// starting up successfully, or it can't access the test files.
9346// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319347class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119348 public:
[email protected]d9fca99a2012-02-24 16:16:209349 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:479350 : ftp_transaction_factory_(&host_resolver_),
9351 test_server_(SpawnedTestServer::TYPE_FTP,
9352 SpawnedTestServer::kLocalhost,
9353 base::FilePath(kTestFilePath)) {
9354 // Can't use |default_context_|'s HostResolver to set up the
9355 // FTPTransactionFactory because it hasn't been created yet.
9356 default_context_.set_host_resolver(&host_resolver_);
9357 }
9358
9359 // URLRequestTest interface:
9360 void SetUpFactory() override {
9361 // Add FTP support to the default URLRequestContext.
9362 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:209363 "ftp",
9364 make_scoped_ptr(new FtpProtocolHandler(&ftp_transaction_factory_)));
mmenke9f2ec60c2015-06-01 20:59:479365 }
9366
9367 std::string GetTestFileContents() {
9368 base::FilePath path;
9369 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9370 path = path.Append(kTestFilePath);
9371 path = path.AppendASCII(kFtpTestFile);
9372 std::string contents;
9373 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9374 return contents;
[email protected]95409e12010-08-17 20:07:119375 }
9376
[email protected]b89ca032009-08-31 21:41:319377 protected:
mmenke9f2ec60c2015-06-01 20:59:479378 MockHostResolver host_resolver_;
9379 FtpNetworkLayer ftp_transaction_factory_;
9380
[email protected]ce7d0cbc2013-05-03 18:57:229381 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:319382};
9383
[email protected]d2a133182012-08-05 16:44:089384// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099385TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089386 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089387
9388 TestDelegate d;
9389 {
davidben151423e2015-03-23 18:48:369390 scoped_ptr<URLRequest> r(
9391 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199392 r->Start();
9393 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089394
[email protected]255620da2013-08-19 13:14:299395 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089396
[email protected]f7022f32014-08-21 16:32:199397 EXPECT_FALSE(r->is_pending());
9398 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
9399 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:089400 }
9401}
9402
mmenke9f2ec60c2015-06-01 20:59:479403TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:119404 ASSERT_TRUE(test_server_.Start());
9405
[email protected]a25e90e2009-09-09 17:05:379406 TestDelegate d;
9407 {
[email protected]f7022f32014-08-21 16:32:199408 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369409 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199410 r->Start();
9411 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379412
[email protected]255620da2013-08-19 13:14:299413 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379414
[email protected]f7022f32014-08-21 16:32:199415 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379416 EXPECT_EQ(1, d.response_started_count());
9417 EXPECT_FALSE(d.received_data_before_response());
9418 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:199419 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199420 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199421 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199422 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379423 }
9424}
9425
mmenke9f2ec60c2015-06-01 20:59:479426TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:119427 ASSERT_TRUE(test_server_.Start());
9428
[email protected]dd265012009-01-08 20:45:279429 TestDelegate d;
9430 {
[email protected]f7022f32014-08-21 16:32:199431 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479432 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199433 r->Start();
9434 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279435
[email protected]255620da2013-08-19 13:14:299436 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279437
[email protected]f7022f32014-08-21 16:32:199438 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279439 EXPECT_EQ(1, d.response_started_count());
9440 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479441 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:199442 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199443 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199444 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199445 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279446 }
9447}
9448
mmenke9f2ec60c2015-06-01 20:59:479449TEST_F(URLRequestTestFTP, FTPGetTest) {
[email protected]95409e12010-08-17 20:07:119450 ASSERT_TRUE(test_server_.Start());
9451
[email protected]dd265012009-01-08 20:45:279452 TestDelegate d;
9453 {
mmenke9f2ec60c2015-06-01 20:59:479454 scoped_ptr<URLRequest> r(
9455 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9456 kFtpTestFile, "chrome", "chrome"),
9457 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199458 r->Start();
9459 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279460
[email protected]255620da2013-08-19 13:14:299461 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279462
[email protected]f7022f32014-08-21 16:32:199463 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479464 EXPECT_EQ(1, d.response_started_count());
9465 EXPECT_FALSE(d.received_data_before_response());
9466 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:199467 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199468 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199469 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199470 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:259471
9472 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:199473 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:259474 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:279475 }
9476}
9477
mmenke9f2ec60c2015-06-01 20:59:479478TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:119479 ASSERT_TRUE(test_server_.Start());
9480
[email protected]dd265012009-01-08 20:45:279481 TestDelegate d;
9482 {
[email protected]f7022f32014-08-21 16:32:199483 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479484 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199485 "wrong_password"),
davidben151423e2015-03-23 18:48:369486 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199487 r->Start();
9488 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279489
[email protected]255620da2013-08-19 13:14:299490 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279491
[email protected]f7022f32014-08-21 16:32:199492 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279493 EXPECT_EQ(1, d.response_started_count());
9494 EXPECT_FALSE(d.received_data_before_response());
9495 EXPECT_EQ(d.bytes_received(), 0);
9496 }
9497}
9498
mmenke9f2ec60c2015-06-01 20:59:479499TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:119500 ASSERT_TRUE(test_server_.Start());
9501
[email protected]8b8a197d2009-08-26 15:57:589502 TestDelegate d;
9503 // Set correct login credentials. The delegate will be asked for them when
9504 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589505 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589506 {
[email protected]f7022f32014-08-21 16:32:199507 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479508 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199509 "wrong_password"),
davidben151423e2015-03-23 18:48:369510 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199511 r->Start();
9512 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589513
[email protected]255620da2013-08-19 13:14:299514 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589515
[email protected]f7022f32014-08-21 16:32:199516 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589517 EXPECT_EQ(1, d.response_started_count());
9518 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479519 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589520 }
9521}
9522
mmenke9f2ec60c2015-06-01 20:59:479523TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:119524 ASSERT_TRUE(test_server_.Start());
9525
[email protected]dd265012009-01-08 20:45:279526 TestDelegate d;
9527 {
mmenke9f2ec60c2015-06-01 20:59:479528 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9529 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9530 "chrome"),
9531 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199532 r->Start();
9533 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279534
[email protected]255620da2013-08-19 13:14:299535 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279536
[email protected]f7022f32014-08-21 16:32:199537 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279538 EXPECT_EQ(1, d.response_started_count());
9539 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479540 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279541 }
9542}
[email protected]8b8a197d2009-08-26 15:57:589543
mmenke9f2ec60c2015-06-01 20:59:479544TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:119545 ASSERT_TRUE(test_server_.Start());
9546
[email protected]8b8a197d2009-08-26 15:57:589547 TestDelegate d;
9548 // Set correct login credentials. The delegate will be asked for them when
9549 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589550 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589551 {
mmenke9f2ec60c2015-06-01 20:59:479552 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9553 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9554 "chrome"),
9555 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199556 r->Start();
9557 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589558
[email protected]255620da2013-08-19 13:14:299559 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589560
[email protected]f7022f32014-08-21 16:32:199561 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589562 EXPECT_EQ(1, d.response_started_count());
9563 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479564 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589565 }
9566}
[email protected]60a3df52009-09-22 16:13:249567
mmenke9f2ec60c2015-06-01 20:59:479568TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:119569 ASSERT_TRUE(test_server_.Start());
9570
[email protected]60a3df52009-09-22 16:13:249571 scoped_ptr<TestDelegate> d(new TestDelegate);
9572 {
9573 // Pass correct login identity in the URL.
mmenke9f2ec60c2015-06-01 20:59:479574 scoped_ptr<URLRequest> r(
9575 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9576 kFtpTestFile, "chrome", "chrome"),
9577 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199578 r->Start();
9579 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249580
[email protected]255620da2013-08-19 13:14:299581 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249582
[email protected]f7022f32014-08-21 16:32:199583 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249584 EXPECT_EQ(1, d->response_started_count());
9585 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479586 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249587 }
9588
9589 d.reset(new TestDelegate);
9590 {
9591 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199592 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479593 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199594 r->Start();
9595 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249596
[email protected]255620da2013-08-19 13:14:299597 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249598
[email protected]f7022f32014-08-21 16:32:199599 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249600 EXPECT_EQ(1, d->response_started_count());
9601 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479602 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249603 }
9604}
9605
mmenke9f2ec60c2015-06-01 20:59:479606TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:119607 ASSERT_TRUE(test_server_.Start());
9608
[email protected]60a3df52009-09-22 16:13:249609 scoped_ptr<TestDelegate> d(new TestDelegate);
9610 // Set correct login credentials. The delegate will be asked for them when
9611 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589612 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249613 {
[email protected]f7022f32014-08-21 16:32:199614 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479615 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199616 "wrong_password"),
davidben151423e2015-03-23 18:48:369617 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199618 r->Start();
9619 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249620
[email protected]255620da2013-08-19 13:14:299621 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249622
[email protected]f7022f32014-08-21 16:32:199623 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249624 EXPECT_EQ(1, d->response_started_count());
9625 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479626 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249627 }
9628
9629 // Use a new delegate without explicit credentials. The cached ones should be
9630 // used.
9631 d.reset(new TestDelegate);
9632 {
9633 // Don't pass wrong credentials in the URL, they would override valid cached
9634 // ones.
[email protected]f7022f32014-08-21 16:32:199635 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479636 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199637 r->Start();
9638 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249639
[email protected]255620da2013-08-19 13:14:299640 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249641
[email protected]f7022f32014-08-21 16:32:199642 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249643 EXPECT_EQ(1, d->response_started_count());
9644 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479645 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249646 }
9647}
[email protected]316c1e5e2012-09-12 15:17:449648#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519649
ttuttlec0c828492015-05-15 01:25:559650TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9651 TestDelegate d;
9652 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9653 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9654 d.set_quit_on_network_start(true);
9655
9656 EXPECT_FALSE(req->response_info().network_accessed);
9657
9658 req->Start();
9659 base::RunLoop().Run();
9660
9661 EXPECT_EQ(1, d.received_before_network_start_count());
9662 EXPECT_EQ(0, d.response_started_count());
9663 EXPECT_FALSE(req->response_info().network_accessed);
9664
9665 req->ResumeNetworkStart();
9666 base::RunLoop().Run();
9667}
9668
9669TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9670 TestDelegate d;
9671 scoped_ptr<URLRequest> req(
9672 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9673
9674 EXPECT_FALSE(req->response_info().network_accessed);
9675
9676 req->Start();
9677 base::RunLoop().Run();
9678
9679 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9680 EXPECT_FALSE(req->response_info().network_accessed);
9681}
9682
9683TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9684 MockHostResolver host_resolver;
9685 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9686 TestURLRequestContext context(true);
9687 context.set_network_delegate(&network_delegate);
9688 context.set_host_resolver(&host_resolver);
9689 host_resolver.rules()->AddSimulatedFailure("*");
9690 context.Init();
9691
9692 TestDelegate d;
9693 scoped_ptr<URLRequest> req(context.CreateRequest(
9694 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9695
9696 EXPECT_FALSE(req->response_info().network_accessed);
9697
9698 req->Start();
9699 base::RunLoop().Run();
9700 EXPECT_TRUE(req->response_info().network_accessed);
9701}
9702
alexanderkcd904b52015-07-24 18:57:229703// Test that URLRequest is canceled correctly and with detached request
9704// URLRequestRedirectJob does not crash in StartAsync.
9705// See http://crbug.com/508900
9706TEST_F(URLRequestTest, URLRequestRedirectJobDetachRequestNoCrash) {
9707 TestDelegate d;
9708 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9709 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
9710
9711 URLRequestRedirectJob* job = new URLRequestRedirectJob(
9712 req.get(), &default_network_delegate_,
9713 GURL("http://this-should-never-be-navigated-to/"),
9714 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp");
9715 AddTestInterceptor()->set_main_intercept_job(job);
9716
9717 req->Start();
9718 req->Cancel();
9719 job->DetachRequest();
9720 base::RunLoop().RunUntilIdle();
9721 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
9722 EXPECT_EQ(0, d.received_redirect_count());
9723}
9724
[email protected]7461a402011-03-24 23:19:519725} // namespace net