blob: 925a4d02407d16626c0753279c34db8658d13496 [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);
mathpc992e602015-10-21 20:34:035618#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());
mathpc992e602015-10-21 20:34:035622#endif
[email protected]37fd55fb2013-06-29 13:13:275623}
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
mathpc992e602015-10-21 20:34:035649// 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
5651// PKPState present because header rejected).
5652#if defined(OS_ANDROID)
5653#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5654#define MAYBE_ProcessPKPAndSendReport DISABLED_ProcessPKPAndSendReport
5655#define MAYBE_ProcessPKPReportOnly DISABLED_ProcessPKPReportOnly
5656#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5657 DISABLED_ProcessPKPReportOnlyWithNoViolation
5658#else
5659#define MAYBE_ProcessPKP ProcessPKP
5660#define MAYBE_ProcessPKPAndSendReport ProcessPKPAndSendReport
5661#define MAYBE_ProcessPKPReportOnly ProcessPKPReportOnly
5662#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5663 ProcessPKPReportOnlyWithNoViolation
5664#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.
mathpc992e602015-10-21 20:34:035672TEST_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.
mathpc992e602015-10-21 20:34:035708TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:015709 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.
mathpc992e602015-10-21 20:34:035787TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:015788 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.
mathpc992e602015-10-21 20:34:035851TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:015852 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);
mathpc992e602015-10-21 20:34:035970#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());
mathpc992e602015-10-21 20:34:035974#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);
mathpc992e602015-10-21 20:34:036013#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());
mathpc992e602015-10-21 20:34:036017#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.
mmenke2281f3762015-11-02 20:38:177285 scoped_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
7286 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547287 network_layer->OnSuspend();
7288
mmenkebc31a2c2015-10-29 13:44:457289 HttpCache http_cache(network_layer.Pass(),
mmenkee65e7af2015-10-13 17:16:427290 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547291
7292 TestURLRequestContext context(true);
7293 context.set_http_transaction_factory(&http_cache);
7294 context.Init();
7295
7296 TestDelegate d;
davidben151423e2015-03-23 18:48:367297 scoped_ptr<URLRequest> req(
7298 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197299 req->Start();
[email protected]80abdad2014-03-15 00:20:547300 base::RunLoop().Run();
7301
7302 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197303 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7304 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547305}
7306
mmenke2281f3762015-11-02 20:38:177307namespace {
[email protected]80abdad2014-03-15 00:20:547308
mmenke2281f3762015-11-02 20:38:177309// HttpTransactionFactory that synchronously fails to create transactions.
7310class FailingHttpTransactionFactory : public HttpTransactionFactory {
7311 public:
7312 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7313 : network_session_(network_session) {}
7314
7315 ~FailingHttpTransactionFactory() override {}
7316
7317 // HttpTransactionFactory methods:
7318 int CreateTransaction(RequestPriority priority,
7319 scoped_ptr<HttpTransaction>* trans) override {
7320 return ERR_FAILED;
7321 }
7322
7323 HttpCache* GetCache() override { return nullptr; }
7324
7325 HttpNetworkSession* GetSession() override { return network_session_; }
7326
7327 private:
7328 HttpNetworkSession* network_session_;
7329
7330 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7331};
7332
7333} // namespace
7334
7335// Check that when a request that fails to create an HttpTransaction can be
7336// cancelled while the failure notification is pending, and doesn't send two
7337// failure notifications.
7338//
7339// This currently only happens when in suspend mode and there's no cache, but
7340// just use a special HttpTransactionFactory, to avoid depending on those
7341// behaviors.
7342TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7343 FailingHttpTransactionFactory http_transaction_factory(
7344 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547345 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177346 context.set_http_transaction_factory(&http_transaction_factory);
7347 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547348 context.Init();
7349
7350 TestDelegate d;
davidben151423e2015-03-23 18:48:367351 scoped_ptr<URLRequest> req(
7352 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177353 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7354 // try to create an HttpNetworkTransaction synchronously on start).
7355 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197356 req->Start();
mmenke2281f3762015-11-02 20:38:177357 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547358 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177359 // Run pending error task, if there is one.
7360 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547361
7362 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177363 EXPECT_EQ(1, d.response_started_count());
7364 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
7365
7366 // NetworkDelegate should see the cancellation, but not the error.
7367 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7368 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547369}
7370
ttuttlec0c828492015-05-15 01:25:557371TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
7372 ASSERT_TRUE(test_server_.Start());
7373
7374 TestDelegate d;
7375 GURL test_url(test_server_.GetURL(std::string()));
7376 scoped_ptr<URLRequest> req(
7377 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7378
7379 req->Start();
7380 base::RunLoop().Run();
7381
7382 EXPECT_TRUE(req->response_info().network_accessed);
7383}
7384
7385TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
7386 ASSERT_TRUE(test_server_.Start());
7387
7388 // Populate the cache.
7389 TestDelegate d;
7390 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
7391 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
7392 req->Start();
7393 base::RunLoop().Run();
7394
7395 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7396 EXPECT_TRUE(req->response_info().network_accessed);
7397 EXPECT_FALSE(req->response_info().was_cached);
7398
7399 req = default_context_.CreateRequest(test_server_.GetURL("cachetime"),
7400 DEFAULT_PRIORITY, &d);
7401 req->Start();
7402 base::RunLoop().Run();
7403
7404 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7405 EXPECT_FALSE(req->response_info().network_accessed);
7406 EXPECT_TRUE(req->response_info().was_cached);
7407}
7408
7409TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
7410 ASSERT_TRUE(test_server_.Start());
7411
7412 TestDelegate d;
7413 GURL test_url(test_server_.GetURL(std::string()));
7414 scoped_ptr<URLRequest> req(
7415 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7416 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7417
7418 req->Start();
7419 base::RunLoop().Run();
7420
7421 EXPECT_FALSE(req->response_info().network_accessed);
7422}
7423
bengr1bf8e942014-11-07 01:36:507424class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7425 public:
7426 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7427 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7428 // tests into the factory tests.
7429 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7430 }
7431
7432 void SetUpFactory() override {
7433 interceptor_ = new MockURLRequestInterceptor();
7434 job_factory_.reset(new URLRequestInterceptingJobFactory(
7435 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
7436 }
7437
7438 MockURLRequestInterceptor* interceptor() const {
7439 return interceptor_;
7440 }
7441
7442 private:
7443 MockURLRequestInterceptor* interceptor_;
7444};
7445
7446TEST_F(URLRequestInterceptorTestHTTP,
7447 NetworkDelegateNotificationOnRedirectIntercept) {
7448 interceptor()->set_intercept_redirect(true);
7449 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7450 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7451
7452 ASSERT_TRUE(test_server()->Start());
7453
7454 TestDelegate d;
7455 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:367456 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507457 req->Start();
7458 base::RunLoop().Run();
7459
7460 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7461 // Check we got one good response
7462 EXPECT_TRUE(req->status().is_success());
7463 if (req->status().is_success())
7464 EXPECT_EQ(200, req->response_headers()->response_code());
7465
7466 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7467 EXPECT_EQ(1, d.response_started_count());
7468 EXPECT_EQ(0, d.received_redirect_count());
7469
7470 EXPECT_EQ(1, default_network_delegate()->created_requests());
7471 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7472 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7473}
7474
7475TEST_F(URLRequestInterceptorTestHTTP,
7476 NetworkDelegateNotificationOnErrorIntercept) {
7477 // Intercept that error and respond with an OK response.
7478 interceptor()->set_intercept_final_response(true);
7479 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7480 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7481 default_network_delegate()->set_can_be_intercepted_on_error(true);
7482
7483 ASSERT_TRUE(test_server()->Start());
7484
7485 TestDelegate d;
7486 scoped_ptr<URLRequest> req(default_context().CreateRequest(
7487 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:367488 &d));
bengr1bf8e942014-11-07 01:36:507489 req->set_method("GET");
7490 req->Start();
7491 base::RunLoop().Run();
7492
7493 EXPECT_TRUE(interceptor()->did_intercept_final());
7494
7495 // Check we received one good response.
7496 EXPECT_TRUE(req->status().is_success());
7497 if (req->status().is_success())
7498 EXPECT_EQ(200, req->response_headers()->response_code());
7499 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7500 EXPECT_EQ(1, d.response_started_count());
7501 EXPECT_EQ(0, d.received_redirect_count());
7502
7503 EXPECT_EQ(1, default_network_delegate()->created_requests());
7504 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7505 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7506}
7507
7508TEST_F(URLRequestInterceptorTestHTTP,
7509 NetworkDelegateNotificationOnResponseIntercept) {
7510 // Intercept that error and respond with an OK response.
7511 interceptor()->set_intercept_final_response(true);
7512
7513 // Intercept with a real URLRequestHttpJob.
7514 interceptor()->set_use_url_request_http_job(true);
7515
7516 ASSERT_TRUE(test_server()->Start());
7517
7518 TestDelegate d;
7519 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:367520 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507521 req->set_method("GET");
7522 req->Start();
7523 base::RunLoop().Run();
7524
7525 EXPECT_TRUE(interceptor()->did_intercept_final());
7526
7527 // Check we received one good response.
7528 EXPECT_TRUE(req->status().is_success());
7529 if (req->status().is_success())
7530 EXPECT_EQ(200, req->response_headers()->response_code());
7531 EXPECT_EQ("hello", d.data_received());
7532 EXPECT_EQ(1, d.response_started_count());
7533 EXPECT_EQ(0, d.received_redirect_count());
7534
7535 EXPECT_EQ(1, default_network_delegate()->created_requests());
7536 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7537 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7538}
7539
mkwst0c5eab872014-11-21 14:18:547540class URLRequestTestReferrerPolicy : public URLRequestTest {
7541 public:
7542 URLRequestTestReferrerPolicy() {}
7543
7544 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
7545 origin_server_.reset(new SpawnedTestServer(
7546 origin_type, SpawnedTestServer::kLocalhost,
7547 origin_type == SpawnedTestServer::TYPE_HTTPS
7548 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477549 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547550 ASSERT_TRUE(origin_server_->Start());
7551 }
7552
7553 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
7554 SpawnedTestServer::Type destination_type) {
7555 origin_server_.reset(new SpawnedTestServer(
7556 origin_type, SpawnedTestServer::kLocalhost,
7557 origin_type == SpawnedTestServer::TYPE_HTTPS
7558 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477559 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547560 ASSERT_TRUE(origin_server_->Start());
7561
7562 destination_server_.reset(new SpawnedTestServer(
7563 destination_type, SpawnedTestServer::kLocalhost,
7564 destination_type == SpawnedTestServer::TYPE_HTTPS
7565 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477566 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547567 ASSERT_TRUE(destination_server_->Start());
7568 }
7569
7570 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7571 const GURL& referrer,
7572 const GURL& expected) {
7573 // Create and execute the request: we'll only have a |destination_server_|
7574 // if the origins are meant to be distinct. Otherwise, we'll use the
7575 // |origin_server_| for both endpoints.
7576 GURL destination_url =
7577 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
7578 : origin_server_->GetURL("echoheader?Referer");
7579 GURL origin_url =
7580 origin_server_->GetURL("server-redirect?" + destination_url.spec());
7581
7582 TestDelegate d;
7583 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367584 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547585 req->set_referrer_policy(policy);
7586 req->SetReferrer(referrer.spec());
7587 req->Start();
7588 base::RunLoop().Run();
7589
7590 EXPECT_EQ(1, d.response_started_count());
7591 EXPECT_EQ(1, d.received_redirect_count());
7592 EXPECT_EQ(destination_url, req->url());
7593 EXPECT_TRUE(req->status().is_success());
7594 EXPECT_EQ(200, req->response_headers()->response_code());
7595
7596 EXPECT_EQ(expected.spec(), req->referrer());
7597 if (expected.is_empty())
7598 EXPECT_EQ("None", d.data_received());
7599 else
7600 EXPECT_EQ(expected.spec(), d.data_received());
7601 }
7602
7603 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
7604
7605 private:
7606 scoped_ptr<SpawnedTestServer> origin_server_;
7607 scoped_ptr<SpawnedTestServer> destination_server_;
7608};
7609
7610TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
7611 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
7612
7613 VerifyReferrerAfterRedirect(
7614 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7615 origin_server()->GetURL("path/to/file.html"),
7616 origin_server()->GetURL("path/to/file.html"));
7617
7618 VerifyReferrerAfterRedirect(
7619 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7620 origin_server()->GetURL("path/to/file.html"),
7621 origin_server()->GetURL("path/to/file.html"));
7622
7623 VerifyReferrerAfterRedirect(
7624 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7625 origin_server()->GetURL("path/to/file.html"),
7626 origin_server()->GetURL("path/to/file.html"));
7627
7628 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7629 origin_server()->GetURL("path/to/file.html"),
7630 origin_server()->GetURL("path/to/file.html"));
7631}
7632
tfarinae04a95b2015-09-18 22:48:127633// Can't spin up more than one SpawnedTestServer on Android.
7634#if defined(OS_ANDROID)
7635#define MAYBE_HTTPToCrossOriginHTTP DISABLED_HTTPToCrosOriginHTTP
7636#else
7637#define MAYBE_HTTPToCrossOriginHTTP HTTPToCrossOriginHTTP
7638#endif
7639TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPToCrossOriginHTTP) {
mkwst0c5eab872014-11-21 14:18:547640 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7641 SpawnedTestServer::TYPE_HTTP);
7642
7643 VerifyReferrerAfterRedirect(
7644 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7645 origin_server()->GetURL("path/to/file.html"),
7646 origin_server()->GetURL("path/to/file.html"));
7647
7648 VerifyReferrerAfterRedirect(
7649 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7650 origin_server()->GetURL("path/to/file.html"),
7651 origin_server()->GetURL(std::string()));
7652
7653 VerifyReferrerAfterRedirect(
7654 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7655 origin_server()->GetURL("path/to/file.html"),
7656 origin_server()->GetURL(std::string()));
7657
7658 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7659 origin_server()->GetURL("path/to/file.html"),
7660 origin_server()->GetURL("path/to/file.html"));
7661}
7662
7663TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
7664 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
7665
7666 VerifyReferrerAfterRedirect(
7667 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7668 origin_server()->GetURL("path/to/file.html"),
7669 origin_server()->GetURL("path/to/file.html"));
7670
7671 VerifyReferrerAfterRedirect(
7672 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7673 origin_server()->GetURL("path/to/file.html"),
7674 origin_server()->GetURL("path/to/file.html"));
7675
7676 VerifyReferrerAfterRedirect(
7677 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7678 origin_server()->GetURL("path/to/file.html"),
7679 origin_server()->GetURL("path/to/file.html"));
7680
7681 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7682 origin_server()->GetURL("path/to/file.html"),
7683 origin_server()->GetURL("path/to/file.html"));
7684}
7685
tfarinae04a95b2015-09-18 22:48:127686// Can't spin up more than one SpawnedTestServer on Android.
7687#if defined(OS_ANDROID)
7688#define MAYBE_HTTPSToCrossOriginHTTPS DISABLED_HTTPSToCrosOriginHTTPS
7689#else
7690#define MAYBE_HTTPSToCrossOriginHTTPS HTTPSToCrossOriginHTTPS
7691#endif
7692TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPSToCrossOriginHTTPS) {
mkwst0c5eab872014-11-21 14:18:547693 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7694 SpawnedTestServer::TYPE_HTTPS);
7695
7696 VerifyReferrerAfterRedirect(
7697 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7698 origin_server()->GetURL("path/to/file.html"),
7699 origin_server()->GetURL("path/to/file.html"));
7700
7701 VerifyReferrerAfterRedirect(
7702 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7703 origin_server()->GetURL("path/to/file.html"),
7704 origin_server()->GetURL(std::string()));
7705
7706 VerifyReferrerAfterRedirect(
7707 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7708 origin_server()->GetURL("path/to/file.html"),
7709 origin_server()->GetURL(std::string()));
7710
7711 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7712 origin_server()->GetURL("path/to/file.html"),
7713 origin_server()->GetURL("path/to/file.html"));
7714}
7715
tfarinae04a95b2015-09-18 22:48:127716// Can't spin up more than one SpawnedTestServer on Android.
7717#if defined(OS_ANDROID)
7718#define MAYBE_HTTPToHTTPS DISABLED_HTTPToHTTPS
7719#else
7720#define MAYBE_HTTPToHTTPS HTTPToHTTPS
7721#endif
7722TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPToHTTPS) {
mkwst0c5eab872014-11-21 14:18:547723 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7724 SpawnedTestServer::TYPE_HTTPS);
7725
7726 VerifyReferrerAfterRedirect(
7727 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7728 origin_server()->GetURL("path/to/file.html"),
7729 origin_server()->GetURL("path/to/file.html"));
7730
7731 VerifyReferrerAfterRedirect(
7732 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7733 origin_server()->GetURL("path/to/file.html"),
7734 origin_server()->GetURL(std::string()));
7735
7736 VerifyReferrerAfterRedirect(
7737 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7738 origin_server()->GetURL("path/to/file.html"),
7739 origin_server()->GetURL(std::string()));
7740
7741 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7742 origin_server()->GetURL("path/to/file.html"),
7743 origin_server()->GetURL("path/to/file.html"));
7744}
7745
tfarinae04a95b2015-09-18 22:48:127746// Can't spin up more than one SpawnedTestServer on Android.
7747#if defined(OS_ANDROID)
7748#define MAYBE_HTTPSToHTTP DISABLED_HTTPSToHTTP
7749#else
7750#define MAYBE_HTTPSToHTTP HTTPSToHTTP
7751#endif
7752TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPSToHTTP) {
mkwst0c5eab872014-11-21 14:18:547753 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7754 SpawnedTestServer::TYPE_HTTP);
7755
7756 VerifyReferrerAfterRedirect(
7757 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7758 origin_server()->GetURL("path/to/file.html"), GURL());
7759
7760 VerifyReferrerAfterRedirect(
7761 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7762 origin_server()->GetURL("path/to/file.html"), GURL());
7763
7764 VerifyReferrerAfterRedirect(
7765 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7766 origin_server()->GetURL("path/to/file.html"),
7767 origin_server()->GetURL(std::string()));
7768
7769 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7770 origin_server()->GetURL("path/to/file.html"),
7771 origin_server()->GetURL("path/to/file.html"));
7772}
7773
[email protected]73e0bba2009-02-19 22:57:097774class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507775 public:
[email protected]ef2bf422012-05-11 03:27:097776 HTTPSRequestTest() : default_context_(true) {
7777 default_context_.set_network_delegate(&default_network_delegate_);
7778 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507779 }
dcheng67be2b1f2014-10-27 21:47:297780 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507781
7782 protected:
[email protected]ceefd7fd2012-11-29 00:36:247783 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097784 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467785};
7786
[email protected]c044616e2013-02-20 02:01:267787TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227788 SpawnedTestServer test_server(
7789 SpawnedTestServer::TYPE_HTTPS,
7790 SpawnedTestServer::kLocalhost,
7791 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117792 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467793
[email protected]ea224582008-12-07 20:25:467794 TestDelegate d;
7795 {
[email protected]f7022f32014-08-21 16:32:197796 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367797 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197798 r->Start();
7799 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467800
[email protected]255620da2013-08-19 13:14:297801 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467802
7803 EXPECT_EQ(1, d.response_started_count());
7804 EXPECT_FALSE(d.received_data_before_response());
7805 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197806 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197807 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197808 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197809 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197810 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467811 }
[email protected]ea224582008-12-07 20:25:467812}
7813
[email protected]5774ada2010-07-15 06:30:547814TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227815 SpawnedTestServer::SSLOptions ssl_options(
7816 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7817 SpawnedTestServer test_server(
7818 SpawnedTestServer::TYPE_HTTPS,
7819 ssl_options,
7820 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117821 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337822
7823 bool err_allowed = true;
7824 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7825 TestDelegate d;
7826 {
7827 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197828 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367829 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337830
[email protected]f7022f32014-08-21 16:32:197831 r->Start();
7832 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337833
[email protected]255620da2013-08-19 13:14:297834 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337835
7836 EXPECT_EQ(1, d.response_started_count());
7837 EXPECT_FALSE(d.received_data_before_response());
7838 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177839 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337840 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197841 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177842 } else {
[email protected]bacff652009-03-31 17:50:337843 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177844 }
[email protected]bacff652009-03-31 17:50:337845 }
7846 }
7847}
7848
[email protected]5774ada2010-07-15 06:30:547849TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227850 SpawnedTestServer::SSLOptions ssl_options(
7851 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7852 SpawnedTestServer test_server(
7853 SpawnedTestServer::TYPE_HTTPS,
7854 ssl_options,
7855 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117856 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337857
7858 // Iterate from false to true, just so that we do the opposite of the
7859 // previous test in order to increase test coverage.
7860 bool err_allowed = false;
7861 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7862 TestDelegate d;
7863 {
7864 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197865 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367866 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337867
[email protected]f7022f32014-08-21 16:32:197868 r->Start();
7869 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337870
[email protected]255620da2013-08-19 13:14:297871 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337872
7873 EXPECT_EQ(1, d.response_started_count());
7874 EXPECT_FALSE(d.received_data_before_response());
7875 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177876 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337877 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197878 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177879 } else {
[email protected]bacff652009-03-31 17:50:337880 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177881 }
[email protected]bacff652009-03-31 17:50:337882 }
7883 }
7884}
[email protected]73e0bba2009-02-19 22:57:097885
[email protected]316c1e5e2012-09-12 15:17:447886// This tests that a load of www.google.com with a certificate error sets
7887// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7888// the interstitial to be fatal.
7889TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227890 SpawnedTestServer::SSLOptions ssl_options(
7891 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7892 SpawnedTestServer test_server(
7893 SpawnedTestServer::TYPE_HTTPS,
7894 ssl_options,
7895 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447896 ASSERT_TRUE(test_server.Start());
7897
7898 // We require that the URL be www.google.com in order to pick up the
7899 // preloaded HSTS entries in the TransportSecurityState. This means that we
7900 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247901 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447902
7903 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247904 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447905 TestURLRequestContext context(true);
7906 context.set_network_delegate(&network_delegate);
7907 context.set_host_resolver(&host_resolver);
7908 TransportSecurityState transport_security_state;
7909 context.set_transport_security_state(&transport_security_state);
7910 context.Init();
7911
7912 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197913 scoped_ptr<URLRequest> r(context.CreateRequest(
7914 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367915 test_server.host_port_pair().port())),
7916 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447917
[email protected]f7022f32014-08-21 16:32:197918 r->Start();
7919 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447920
[email protected]255620da2013-08-19 13:14:297921 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447922
7923 EXPECT_EQ(1, d.response_started_count());
7924 EXPECT_FALSE(d.received_data_before_response());
7925 EXPECT_TRUE(d.have_certificate_errors());
7926 EXPECT_TRUE(d.certificate_errors_are_fatal());
7927}
7928
7929// This tests that cached HTTPS page loads do not cause any updates to the
7930// TransportSecurityState.
7931TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7932 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7933 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227934 SpawnedTestServer::SSLOptions ssl_options(
7935 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7936 SpawnedTestServer test_server(
7937 SpawnedTestServer::TYPE_HTTPS,
7938 ssl_options,
7939 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447940 ASSERT_TRUE(test_server.Start());
7941
[email protected]9e6968d2014-05-07 21:46:267942 // We require that the URL be www.google.com in order to pick up the static
7943 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7944 // that we have to use a MockHostResolver in order to direct www.google.com to
7945 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447946
7947 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247948 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447949 TestURLRequestContext context(true);
7950 context.set_network_delegate(&network_delegate);
7951 context.set_host_resolver(&host_resolver);
7952 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267953
martijnc0d6b622015-06-30 19:14:407954 TransportSecurityState::STSState static_sts_state;
7955 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:267956 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:407957 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:447958 context.set_transport_security_state(&transport_security_state);
7959 context.Init();
7960
martijnc0d6b622015-06-30 19:14:407961 TransportSecurityState::STSState dynamic_sts_state;
7962 TransportSecurityState::PKPState dynamic_pkp_state;
7963 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
7964 &dynamic_sts_state));
7965 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
7966 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:267967
[email protected]316c1e5e2012-09-12 15:17:447968 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197969 scoped_ptr<URLRequest> r(context.CreateRequest(
7970 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367971 test_server.host_port_pair().port())),
7972 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447973
[email protected]f7022f32014-08-21 16:32:197974 r->Start();
7975 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447976
[email protected]255620da2013-08-19 13:14:297977 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447978
7979 EXPECT_EQ(1, d.response_started_count());
7980 EXPECT_FALSE(d.received_data_before_response());
7981 EXPECT_TRUE(d.have_certificate_errors());
7982 EXPECT_TRUE(d.certificate_errors_are_fatal());
7983
[email protected]9e6968d2014-05-07 21:46:267984 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:407985 TransportSecurityState::STSState new_static_sts_state;
7986 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:267987 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:407988 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
7989 TransportSecurityState::STSState new_dynamic_sts_state;
7990 TransportSecurityState::PKPState new_dynamic_pkp_state;
7991 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
7992 "www.google.com", &new_dynamic_sts_state));
7993 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
7994 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:267995
martijnc0d6b622015-06-30 19:14:407996 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
7997 EXPECT_EQ(new_static_sts_state.include_subdomains,
7998 static_sts_state.include_subdomains);
7999 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8000 static_pkp_state.include_subdomains);
8001 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.spki_hashes,
8002 static_pkp_state.spki_hashes));
8003 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.bad_spki_hashes,
8004 static_pkp_state.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:448005}
8006
[email protected]8ccc69f2012-11-28 19:52:148007// Make sure HSTS preserves a POST request's method and body.
8008TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8009 static const char kData[] = "hello world";
8010
[email protected]ce7d0cbc2013-05-03 18:57:228011 SpawnedTestServer::SSLOptions ssl_options(
8012 SpawnedTestServer::SSLOptions::CERT_OK);
8013 SpawnedTestServer test_server(
8014 SpawnedTestServer::TYPE_HTTPS,
8015 ssl_options,
8016 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148017 ASSERT_TRUE(test_server.Start());
8018
8019
8020 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8021 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:228022 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
8023 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148024 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148025
8026 // Force https for www.somewhere.com.
8027 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208028 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8029 bool include_subdomains = false;
8030 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8031 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148032
8033 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8034
8035 TestURLRequestContext context(true);
8036 context.set_host_resolver(&host_resolver);
8037 context.set_transport_security_state(&transport_security_state);
8038 context.set_network_delegate(&network_delegate);
8039 context.Init();
8040
8041 TestDelegate d;
8042 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8043 // cause a certificate error. Ignore the error.
8044 d.set_allow_certificate_errors(true);
8045
[email protected]f7022f32014-08-21 16:32:198046 scoped_ptr<URLRequest> req(context.CreateRequest(
8047 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368048 test_server.host_port_pair().port())),
8049 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198050 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078051 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148052
[email protected]f7022f32014-08-21 16:32:198053 req->Start();
[email protected]255620da2013-08-19 13:14:298054 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148055
[email protected]f7022f32014-08-21 16:32:198056 EXPECT_EQ("https", req->url().scheme());
8057 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148058 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408059
8060 LoadTimingInfo load_timing_info;
8061 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8062 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8063 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148064}
8065
rob4e0be1f2014-09-11 23:40:228066// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8067TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8068 static const char kOriginHeaderValue[] = "http://www.example.com";
8069
8070 SpawnedTestServer::SSLOptions ssl_options(
8071 SpawnedTestServer::SSLOptions::CERT_OK);
8072 SpawnedTestServer test_server(
8073 SpawnedTestServer::TYPE_HTTPS,
8074 ssl_options,
8075 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8076 ASSERT_TRUE(test_server.Start());
8077
8078 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8079 // address, so a MockHostResolver is needed to redirect example.net to the
8080 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
8081 MockHostResolver host_resolver;
8082
8083 TransportSecurityState transport_security_state;
8084 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8085 bool include_subdomains = false;
8086 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8087
8088 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8089
8090 MockCertVerifier cert_verifier;
8091 cert_verifier.set_default_result(OK);
8092
8093 TestURLRequestContext context(true);
8094 context.set_host_resolver(&host_resolver);
8095 context.set_transport_security_state(&transport_security_state);
8096 context.set_network_delegate(&network_delegate);
8097 context.set_cert_verifier(&cert_verifier);
8098 context.Init();
8099
8100 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8101 test_server.host_port_pair().port()));
8102 url::Replacements<char> replacements;
8103 const char kNewScheme[] = "https";
8104 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8105 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8106
8107 TestDelegate d;
8108 // Quit on redirect to allow response header inspection upon redirect.
8109 d.set_quit_on_redirect(true);
8110
davidben151423e2015-03-23 18:48:368111 scoped_ptr<URLRequest> req(
8112 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228113 // Set Origin header to simulate a cross-origin request.
8114 HttpRequestHeaders request_headers;
8115 request_headers.SetHeader("Origin", kOriginHeaderValue);
8116 req->SetExtraRequestHeaders(request_headers);
8117
8118 req->Start();
8119 base::RunLoop().Run();
8120
8121 EXPECT_EQ(1, d.received_redirect_count());
8122
8123 const HttpResponseHeaders* headers = req->response_headers();
8124 std::string redirect_location;
8125 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8126 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8127
8128 std::string received_cors_header;
8129 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8130 &received_cors_header));
8131 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8132}
8133
Adam Ricecb76ac62015-02-20 05:33:258134// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
8135// are performed in net/websockets/websocket_end_to_end_test.cc.
8136TEST(WebSocketURLRequestTest, HSTSApplied) {
8137 TestNetworkDelegate network_delegate;
8138 TransportSecurityState transport_security_state;
8139 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8140 bool include_subdomains = false;
8141 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8142 TestURLRequestContext context(true);
8143 context.set_transport_security_state(&transport_security_state);
8144 context.set_network_delegate(&network_delegate);
8145 context.Init();
8146 GURL ws_url("ws://example.net/echo");
8147 TestDelegate delegate;
8148 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:368149 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:258150 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
8151 EXPECT_TRUE(ws_url.SchemeIs("wss"));
8152}
8153
[email protected]316c1e5e2012-09-12 15:17:448154namespace {
8155
8156class SSLClientAuthTestDelegate : public TestDelegate {
8157 public:
8158 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8159 }
dchengb03027d2014-10-21 12:00:208160 void OnCertificateRequested(URLRequest* request,
8161 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448162 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178163 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448164 }
8165 int on_certificate_requested_count() {
8166 return on_certificate_requested_count_;
8167 }
8168 private:
8169 int on_certificate_requested_count_;
8170};
8171
8172} // namespace
8173
8174// TODO(davidben): Test the rest of the code. Specifically,
8175// - Filtering which certificates to select.
8176// - Sending a certificate back.
8177// - Getting a certificate request in an SSL renegotiation sending the
8178// HTTP request.
8179TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:228180 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448181 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:228182 SpawnedTestServer test_server(
8183 SpawnedTestServer::TYPE_HTTPS,
8184 ssl_options,
8185 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448186 ASSERT_TRUE(test_server.Start());
8187
8188 SSLClientAuthTestDelegate d;
8189 {
[email protected]f7022f32014-08-21 16:32:198190 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368191 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448192
[email protected]f7022f32014-08-21 16:32:198193 r->Start();
8194 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448195
[email protected]255620da2013-08-19 13:14:298196 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448197
8198 EXPECT_EQ(1, d.on_certificate_requested_count());
8199 EXPECT_FALSE(d.received_data_before_response());
8200 EXPECT_EQ(0, d.bytes_received());
8201
8202 // Send no certificate.
8203 // TODO(davidben): Get temporary client cert import (with keys) working on
8204 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:198205 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:448206
[email protected]255620da2013-08-19 13:14:298207 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448208
8209 EXPECT_EQ(1, d.response_started_count());
8210 EXPECT_FALSE(d.received_data_before_response());
8211 EXPECT_NE(0, d.bytes_received());
8212 }
8213}
8214
8215TEST_F(HTTPSRequestTest, ResumeTest) {
8216 // Test that we attempt a session resume when making two connections to the
8217 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228218 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448219 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228220 SpawnedTestServer test_server(
8221 SpawnedTestServer::TYPE_HTTPS,
8222 ssl_options,
8223 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448224 ASSERT_TRUE(test_server.Start());
8225
8226 SSLClientSocket::ClearSessionCache();
8227
8228 {
8229 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198230 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368231 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448232
[email protected]f7022f32014-08-21 16:32:198233 r->Start();
8234 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448235
[email protected]255620da2013-08-19 13:14:298236 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448237
8238 EXPECT_EQ(1, d.response_started_count());
8239 }
8240
8241 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8242 CloseAllConnections();
8243
8244 {
8245 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198246 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368247 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448248
[email protected]f7022f32014-08-21 16:32:198249 r->Start();
8250 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448251
[email protected]255620da2013-08-19 13:14:298252 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448253
8254 // The response will look like;
8255 // insert abc
8256 // lookup abc
8257 // insert xyz
8258 //
8259 // With a newline at the end which makes the split think that there are
8260 // four lines.
8261
8262 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298263 std::vector<std::string> lines = base::SplitString(
8264 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448265 ASSERT_EQ(4u, lines.size()) << d.data_received();
8266
8267 std::string session_id;
8268
8269 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298270 std::vector<std::string> parts = base::SplitString(
8271 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448272 ASSERT_EQ(2u, parts.size());
8273 if (i == 0) {
8274 EXPECT_EQ("insert", parts[0]);
8275 session_id = parts[1];
8276 } else {
8277 EXPECT_EQ("lookup", parts[0]);
8278 EXPECT_EQ(session_id, parts[1]);
8279 }
8280 }
8281 }
8282}
8283
Adam Langley32352ad2014-10-14 22:31:008284// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8285// the result of fetching "ssl-session-cache" from the test server, indicates
8286// that exactly two different sessions were inserted, with no lookups etc.
8287static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298288 std::vector<std::string> lines = base::SplitString(
8289 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008290 ASSERT_EQ(3u, lines.size()) << session_info;
8291
8292 std::string session_id;
8293 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298294 std::vector<std::string> parts = base::SplitString(
8295 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008296 ASSERT_EQ(2u, parts.size());
8297 EXPECT_EQ("insert", parts[0]);
8298 if (i == 0) {
8299 session_id = parts[1];
8300 } else {
8301 EXPECT_NE(session_id, parts[1]);
8302 }
8303 }
8304}
8305
[email protected]316c1e5e2012-09-12 15:17:448306TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8307 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8308 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228309 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448310 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228311 SpawnedTestServer test_server(
8312 SpawnedTestServer::TYPE_HTTPS,
8313 ssl_options,
8314 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448315 ASSERT_TRUE(test_server.Start());
8316
8317 SSLClientSocket::ClearSessionCache();
8318
8319 {
8320 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198321 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368322 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448323
[email protected]f7022f32014-08-21 16:32:198324 r->Start();
8325 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448326
[email protected]255620da2013-08-19 13:14:298327 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448328
8329 EXPECT_EQ(1, d.response_started_count());
8330 }
8331
8332 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8333 HttpNetworkSession::Params params;
8334 params.host_resolver = default_context_.host_resolver();
8335 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118336 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:448337 params.proxy_service = default_context_.proxy_service();
8338 params.ssl_config_service = default_context_.ssl_config_service();
8339 params.http_auth_handler_factory =
8340 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:418341 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:448342 params.http_server_properties = default_context_.http_server_properties();
8343 params.ssl_session_cache_shard = "alternate";
8344
mmenkee65e7af2015-10-13 17:16:428345 HttpNetworkSession network_session(params);
[email protected]cba24642014-08-15 20:49:598346 scoped_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428347 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448348
8349 default_context_.set_http_transaction_factory(cache.get());
8350
8351 {
8352 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198353 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368354 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448355
[email protected]f7022f32014-08-21 16:32:198356 r->Start();
8357 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448358
[email protected]255620da2013-08-19 13:14:298359 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448360
8361 // The response will look like;
8362 // insert abc
8363 // insert xyz
8364 //
8365 // With a newline at the end which makes the split think that there are
8366 // three lines.
8367
8368 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008369 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448370 }
8371}
8372
davidben8ecc3072014-09-03 23:19:098373#if defined(OS_WIN)
8374
8375namespace {
8376
8377bool IsECDSACipherSuite(uint16_t cipher_suite) {
8378 const char* key_exchange;
8379 const char* cipher;
8380 const char* mac;
8381 bool is_aead;
8382 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
8383 return std::string(key_exchange).find("ECDSA") != std::string::npos;
8384}
8385
8386} // namespace
8387
8388// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
8389// verified.
davidben9399c952014-10-07 04:09:118390TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:098391 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
8392 LOG(INFO) << "Skipping test on this version.";
8393 return;
8394 }
8395
8396 SpawnedTestServer test_server(
8397 SpawnedTestServer::TYPE_HTTPS,
8398 SpawnedTestServer::kLocalhost,
8399 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8400 ASSERT_TRUE(test_server.Start());
8401
8402 TestDelegate d;
8403 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368404 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:098405 r->Start();
8406 EXPECT_TRUE(r->is_pending());
8407
8408 base::RunLoop().Run();
8409
8410 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298411 std::vector<std::string> lines = base::SplitString(
8412 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
davidben8ecc3072014-09-03 23:19:098413
8414 for (size_t i = 0; i < lines.size(); i++) {
8415 int cipher_suite;
8416 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
8417 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
8418 << "ClientHello advertised " << cipher_suite;
8419 }
8420}
8421
8422#endif // OS_WIN
8423
Adam Langley32352ad2014-10-14 22:31:008424class TestSSLConfigService : public SSLConfigService {
8425 public:
8426 TestSSLConfigService(bool ev_enabled,
8427 bool online_rev_checking,
8428 bool rev_checking_required_local_anchors)
8429 : ev_enabled_(ev_enabled),
8430 online_rev_checking_(online_rev_checking),
8431 rev_checking_required_local_anchors_(
8432 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:028433 min_version_(kDefaultSSLVersionMin),
8434 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
8435
8436 void set_min_version(uint16 version) {
8437 min_version_ = version;
8438 }
Adam Langley32352ad2014-10-14 22:31:008439
8440 void set_fallback_min_version(uint16 version) {
8441 fallback_min_version_ = version;
8442 }
8443
8444 // SSLConfigService:
dchengb03027d2014-10-21 12:00:208445 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:008446 *config = SSLConfig();
8447 config->rev_checking_enabled = online_rev_checking_;
8448 config->verify_ev_cert = ev_enabled_;
8449 config->rev_checking_required_local_anchors =
8450 rev_checking_required_local_anchors_;
8451 if (fallback_min_version_) {
8452 config->version_fallback_min = fallback_min_version_;
8453 }
Adam Langleyac6f24b42014-10-31 20:24:028454 if (min_version_) {
8455 config->version_min = min_version_;
8456 }
Adam Langley32352ad2014-10-14 22:31:008457 }
8458
8459 protected:
dchengb03027d2014-10-21 12:00:208460 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:008461
8462 private:
8463 const bool ev_enabled_;
8464 const bool online_rev_checking_;
8465 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:028466 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:008467 uint16 fallback_min_version_;
8468};
8469
8470class FallbackTestURLRequestContext : public TestURLRequestContext {
8471 public:
8472 explicit FallbackTestURLRequestContext(bool delay_initialization)
8473 : TestURLRequestContext(delay_initialization) {}
8474
8475 void set_fallback_min_version(uint16 version) {
8476 TestSSLConfigService *ssl_config_service =
8477 new TestSSLConfigService(true /* check for EV */,
8478 false /* online revocation checking */,
8479 false /* require rev. checking for local
8480 anchors */);
8481 ssl_config_service->set_fallback_min_version(version);
8482 set_ssl_config_service(ssl_config_service);
8483 }
8484};
8485
[email protected]48d2b7c52014-06-27 01:16:558486class HTTPSFallbackTest : public testing::Test {
8487 public:
Adam Langley32352ad2014-10-14 22:31:008488 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298489 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558490
8491 protected:
8492 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8493 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008494 context_.Init();
8495 delegate_.set_allow_certificate_errors(true);
8496
[email protected]48d2b7c52014-06-27 01:16:558497 SpawnedTestServer test_server(
8498 SpawnedTestServer::TYPE_HTTPS,
8499 ssl_options,
8500 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8501 ASSERT_TRUE(test_server.Start());
8502
davidben151423e2015-03-23 18:48:368503 request_ = context_.CreateRequest(test_server.GetURL(std::string()),
8504 DEFAULT_PRIORITY, &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558505 request_->Start();
8506
8507 base::RunLoop().Run();
8508 }
8509
Adam Langley32352ad2014-10-14 22:31:008510 void set_fallback_min_version(uint16 version) {
8511 context_.set_fallback_min_version(version);
8512 }
8513
[email protected]48d2b7c52014-06-27 01:16:558514 void ExpectConnection(int version) {
8515 EXPECT_EQ(1, delegate_.response_started_count());
8516 EXPECT_NE(0, delegate_.bytes_received());
8517 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8518 request_->ssl_info().connection_status));
8519 EXPECT_TRUE(request_->ssl_info().connection_status &
8520 SSL_CONNECTION_VERSION_FALLBACK);
8521 }
8522
8523 void ExpectFailure(int error) {
8524 EXPECT_EQ(1, delegate_.response_started_count());
8525 EXPECT_FALSE(request_->status().is_success());
8526 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8527 EXPECT_EQ(error, request_->status().error());
8528 }
8529
8530 private:
8531 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008532 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558533 scoped_ptr<URLRequest> request_;
8534};
8535
davidbenb127ca82015-06-15 19:05:428536// Tests the TLS 1.0 fallback doesn't happen.
8537TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558538 SpawnedTestServer::SSLOptions ssl_options(
8539 SpawnedTestServer::SSLOptions::CERT_OK);
8540 ssl_options.tls_intolerant =
8541 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8542
8543 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428544 ExpectFailure(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION);
8545}
8546
8547// Tests the TLS 1.1 fallback.
8548TEST_F(HTTPSFallbackTest, TLSv1_1Fallback) {
davidbenb127ca82015-06-15 19:05:428549 SpawnedTestServer::SSLOptions ssl_options(
8550 SpawnedTestServer::SSLOptions::CERT_OK);
8551 ssl_options.tls_intolerant =
8552 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8553
8554 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8555 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
8556}
8557
8558// Tests that the TLS 1.1 fallback triggers on closed connections.
8559TEST_F(HTTPSFallbackTest, TLSv1_1FallbackClosed) {
davidbenb127ca82015-06-15 19:05:428560 SpawnedTestServer::SSLOptions ssl_options(
8561 SpawnedTestServer::SSLOptions::CERT_OK);
8562 ssl_options.tls_intolerant =
8563 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8564 ssl_options.tls_intolerance_type =
8565 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8566
8567 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8568 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558569}
8570
8571// This test is disabled on Android because the remote test server doesn't cause
8572// a TCP reset.
8573#if !defined(OS_ANDROID)
davidbenb127ca82015-06-15 19:05:428574// Tests fallback to TLS 1.1 on connection reset.
8575TEST_F(HTTPSFallbackTest, TLSv1_1FallbackReset) {
[email protected]48d2b7c52014-06-27 01:16:558576 SpawnedTestServer::SSLOptions ssl_options(
8577 SpawnedTestServer::SSLOptions::CERT_OK);
8578 ssl_options.tls_intolerant =
davidbenb127ca82015-06-15 19:05:428579 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
[email protected]48d2b7c52014-06-27 01:16:558580 ssl_options.tls_intolerance_type =
8581 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8582
8583 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428584 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558585}
8586#endif // !OS_ANDROID
8587
[email protected]12833302014-07-02 01:57:318588// Tests that we don't fallback on handshake failure with servers that implement
8589// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558590TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558591 SpawnedTestServer::SSLOptions ssl_options(
8592 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438593 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558594 // a version fallback.
8595 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438596 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558597 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8598 // connections are rejected.
8599 ssl_options.fallback_scsv_enabled = true;
8600
8601 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8602
8603 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8604 // intolerance. If the fallback SCSV is processed when the original error
8605 // that caused the fallback should be returned, which should be
8606 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8607 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8608}
8609
[email protected]12833302014-07-02 01:57:318610// Tests that we don't fallback on connection closed with servers that implement
8611// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318612TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318613 SpawnedTestServer::SSLOptions ssl_options(
8614 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438615 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318616 // a version fallback.
8617 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438618 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318619 ssl_options.tls_intolerance_type =
8620 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8621 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8622 // connections are rejected.
8623 ssl_options.fallback_scsv_enabled = true;
8624
8625 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8626
8627 // The original error should be replayed on rejected fallback.
8628 ExpectFailure(ERR_CONNECTION_CLOSED);
8629}
8630
davidbenb937d6c2015-05-14 04:53:428631// Test that fallback probe connections don't cause sessions to be cached.
8632TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008633 SpawnedTestServer::SSLOptions ssl_options(
8634 SpawnedTestServer::SSLOptions::CERT_OK);
8635 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428636 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008637 ssl_options.tls_intolerance_type =
8638 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8639 ssl_options.record_resume = true;
8640
8641 SpawnedTestServer test_server(
8642 SpawnedTestServer::TYPE_HTTPS,
8643 ssl_options,
8644 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8645 ASSERT_TRUE(test_server.Start());
8646
8647 SSLClientSocket::ClearSessionCache();
8648
davidbenb937d6c2015-05-14 04:53:428649 // Make a connection that does a probe fallback to TLSv1 but fails because
8650 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008651 // be inserted locally.
8652 {
8653 TestDelegate delegate;
8654 FallbackTestURLRequestContext context(true);
8655
davidbenb937d6c2015-05-14 04:53:428656 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008657 context.Init();
8658 scoped_ptr<URLRequest> request(context.CreateRequest(
davidben151423e2015-03-23 18:48:368659 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008660 request->Start();
8661
8662 base::RunLoop().Run();
8663
8664 EXPECT_EQ(1, delegate.response_started_count());
8665 EXPECT_FALSE(request->status().is_success());
8666 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8667 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8668 request->status().error());
8669 }
8670
davidbenb937d6c2015-05-14 04:53:428671 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008672 {
8673 TestDelegate delegate;
8674 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428675 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008676
8677 context.Init();
davidben151423e2015-03-23 18:48:368678 scoped_ptr<URLRequest> request(context.CreateRequest(
8679 test_server.GetURL("ssl-session-cache"), 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_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428686 EXPECT_EQ(
8687 SSL_CONNECTION_VERSION_TLS1,
8688 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008689 EXPECT_TRUE(request->ssl_info().connection_status &
8690 SSL_CONNECTION_VERSION_FALLBACK);
8691
8692 std::vector<std::string> lines;
8693 // If no sessions were cached then the server should have seen two sessions
8694 // inserted with no lookups.
8695 AssertTwoDistinctSessionsInserted(delegate.data_received());
8696 }
8697}
8698
[email protected]a8fed1742013-12-27 02:14:248699class HTTPSSessionTest : public testing::Test {
8700 public:
8701 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598702 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248703
8704 default_context_.set_network_delegate(&default_network_delegate_);
8705 default_context_.set_cert_verifier(&cert_verifier_);
8706 default_context_.Init();
8707 }
dcheng67be2b1f2014-10-27 21:47:298708 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248709
8710 protected:
8711 MockCertVerifier cert_verifier_;
8712 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8713 TestURLRequestContext default_context_;
8714};
8715
8716// Tests that session resumption is not attempted if an invalid certificate
8717// is presented.
8718TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8719 SpawnedTestServer::SSLOptions ssl_options;
8720 ssl_options.record_resume = true;
8721 SpawnedTestServer test_server(
8722 SpawnedTestServer::TYPE_HTTPS,
8723 ssl_options,
8724 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8725 ASSERT_TRUE(test_server.Start());
8726
8727 SSLClientSocket::ClearSessionCache();
8728
8729 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598730 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248731 {
8732 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198733 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368734 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248735
[email protected]f7022f32014-08-21 16:32:198736 r->Start();
8737 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248738
8739 base::RunLoop().Run();
8740
8741 EXPECT_EQ(1, d.response_started_count());
8742 }
8743
8744 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8745 CloseAllConnections();
8746
8747 // Now change the certificate to be acceptable (so that the response is
8748 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598749 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248750 {
8751 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198752 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368753 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248754
[email protected]f7022f32014-08-21 16:32:198755 r->Start();
8756 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248757
8758 base::RunLoop().Run();
8759
8760 // The response will look like;
8761 // insert abc
8762 // insert xyz
8763 //
8764 // With a newline at the end which makes the split think that there are
8765 // three lines.
8766 //
8767 // If a session was presented (eg: a bug), then the response would look
8768 // like;
8769 // insert abc
8770 // lookup abc
8771 // insert xyz
8772
8773 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008774 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248775 }
8776}
8777
[email protected]dffe8242012-03-20 15:14:278778// This the fingerprint of the "Testing CA" certificate used by the testserver.
8779// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268780static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278781 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8782 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8783
[email protected]51523f52013-07-31 21:57:288784// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8785// testserver.
8786static const SHA256HashValue kOCSPTestCertSPKI = { {
8787 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8788 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8789 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8790 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8791} };
8792
[email protected]dffe8242012-03-20 15:14:278793// This is the policy OID contained in the certificates that testserver
8794// generates.
8795static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8796
8797class HTTPSOCSPTest : public HTTPSRequestTest {
8798 public:
8799 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098800 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088801 ev_test_policy_(
8802 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8803 kOCSPTestCertFingerprint,
8804 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028805 }
8806
dcheng67be2b1f2014-10-27 21:47:298807 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098808 SetupContext(&context_);
8809 context_.Init();
[email protected]dffe8242012-03-20 15:14:278810
[email protected]cba24642014-08-15 20:49:598811 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208812 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428813 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508814 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278815
davidben71f35ff2015-04-17 20:54:488816#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098817 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278818 EnsureNSSHttpIOInit();
8819#endif
8820 }
8821
[email protected]ce7d0cbc2013-05-03 18:57:228822 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278823 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538824 // We always overwrite out_cert_status.
8825 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228826 SpawnedTestServer test_server(
8827 SpawnedTestServer::TYPE_HTTPS,
8828 ssl_options,
8829 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278830 ASSERT_TRUE(test_server.Start());
8831
8832 TestDelegate d;
8833 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:198834 scoped_ptr<URLRequest> r(context_.CreateRequest(
davidben151423e2015-03-23 18:48:368835 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198836 r->Start();
[email protected]dffe8242012-03-20 15:14:278837
[email protected]255620da2013-08-19 13:14:298838 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278839
8840 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198841 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278842 }
8843
dcheng67be2b1f2014-10-27 21:47:298844 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488845#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278846 ShutdownNSSHttpIO();
8847#endif
8848 }
8849
[email protected]a13234c2012-03-20 21:45:028850 protected:
8851 // SetupContext configures the URLRequestContext that will be used for making
8852 // connetions to testserver. This can be overridden in test subclasses for
8853 // different behaviour.
8854 virtual void SetupContext(URLRequestContext* context) {
8855 context->set_ssl_config_service(
8856 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208857 true /* online revocation checking */,
8858 false /* require rev. checking for local
8859 anchors */));
[email protected]a13234c2012-03-20 21:45:028860 }
8861
[email protected]dffe8242012-03-20 15:14:278862 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098863 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088864 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278865};
8866
[email protected]a13234c2012-03-20 21:45:028867static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018868#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028869 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8870 // have that ability on other platforms.
8871 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8872#else
8873 return 0;
8874#endif
8875}
8876
[email protected]3a86a712013-07-30 07:16:208877// SystemSupportsHardFailRevocationChecking returns true iff the current
8878// operating system supports revocation checking and can distinguish between
8879// situations where a given certificate lacks any revocation information (eg:
8880// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8881// revocation information cannot be obtained (eg: the CRL was unreachable).
8882// If it does not, then tests which rely on 'hard fail' behaviour should be
8883// skipped.
8884static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:488885#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:208886 return true;
8887#else
8888 return false;
8889#endif
8890}
8891
[email protected]a13234c2012-03-20 21:45:028892// SystemUsesChromiumEVMetadata returns true iff the current operating system
8893// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8894// several tests are effected because our testing EV certificate won't be
8895// recognised as EV.
8896static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328897#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578898 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8899 return false;
[email protected]e1b2d732014-03-28 16:20:328900#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8901 // On OS X and Android, we use the system to tell us whether a certificate is
8902 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018903 return false;
8904#else
8905 return true;
8906#endif
8907}
8908
[email protected]b6f2de32012-08-17 04:35:088909static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008910#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578911 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8912 return false;
8913#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028914 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8915#elif defined(OS_ANDROID)
8916 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8917 return false;
8918#else
8919 return true;
8920#endif
8921}
8922
davidbend1fb2f12014-11-08 02:51:008923static bool SystemSupportsOCSPStapling() {
mathpc992e602015-10-21 20:34:038924#if defined(USE_NSS_CERTS) || defined(OS_IOS)
8925 return true;
8926#elif defined(OS_WIN)
8927 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8928#else
8929 return false;
8930#endif
davidbend1fb2f12014-11-08 02:51:008931}
8932
[email protected]dffe8242012-03-20 15:14:278933TEST_F(HTTPSOCSPTest, Valid) {
8934 if (!SystemSupportsOCSP()) {
8935 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8936 return;
8937 }
8938
[email protected]ce7d0cbc2013-05-03 18:57:228939 SpawnedTestServer::SSLOptions ssl_options(
8940 SpawnedTestServer::SSLOptions::CERT_AUTO);
8941 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278942
[email protected]924e9f92012-12-16 22:00:538943 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128944 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278945
8946 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8947
[email protected]a13234c2012-03-20 21:45:028948 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8949 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278950
8951 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8952}
8953
8954TEST_F(HTTPSOCSPTest, Revoked) {
8955 if (!SystemSupportsOCSP()) {
8956 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8957 return;
8958 }
8959
[email protected]ce7d0cbc2013-05-03 18:57:228960 SpawnedTestServer::SSLOptions ssl_options(
8961 SpawnedTestServer::SSLOptions::CERT_AUTO);
8962 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278963
8964 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128965 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278966
[email protected]a592c0432012-12-01 18:10:298967#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278968 // Doesn't pass on OS X yet for reasons that need to be investigated.
8969 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8970#endif
8971 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8972 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8973}
8974
8975TEST_F(HTTPSOCSPTest, Invalid) {
8976 if (!SystemSupportsOCSP()) {
8977 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8978 return;
8979 }
8980
[email protected]ce7d0cbc2013-05-03 18:57:228981 SpawnedTestServer::SSLOptions ssl_options(
8982 SpawnedTestServer::SSLOptions::CERT_AUTO);
8983 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:278984
[email protected]924e9f92012-12-16 22:00:538985 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128986 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278987
[email protected]a13234c2012-03-20 21:45:028988 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278989 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:278990
8991 // Without a positive OCSP response, we shouldn't show the EV status.
8992 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8993 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8994}
[email protected]a13234c2012-03-20 21:45:028995
davidbend1fb2f12014-11-08 02:51:008996TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:038997 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:008998 LOG(WARNING)
8999 << "Skipping test because system doesn't support OCSP stapling";
9000 return;
9001 }
9002
9003 SpawnedTestServer::SSLOptions ssl_options(
9004 SpawnedTestServer::SSLOptions::CERT_AUTO);
9005 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9006 ssl_options.staple_ocsp_response = true;
9007 ssl_options.ocsp_server_unavailable = true;
9008
9009 CertStatus cert_status;
9010 DoConnection(ssl_options, &cert_status);
9011
9012 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9013
9014 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9015 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9016
9017 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9018}
9019
davidben6c3191b2014-11-21 22:38:049020// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489021#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049022#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9023#else
9024#define MAYBE_RevokedStapled RevokedStapled
9025#endif
9026TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:039027 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009028 LOG(WARNING)
9029 << "Skipping test because system doesn't support OCSP stapling";
9030 return;
9031 }
9032
9033 SpawnedTestServer::SSLOptions ssl_options(
9034 SpawnedTestServer::SSLOptions::CERT_AUTO);
9035 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9036 ssl_options.staple_ocsp_response = true;
9037 ssl_options.ocsp_server_unavailable = true;
9038
9039 CertStatus cert_status;
9040 DoConnection(ssl_options, &cert_status);
9041
9042 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9043 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9044 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9045}
9046
[email protected]3a86a712013-07-30 07:16:209047class HTTPSHardFailTest : public HTTPSOCSPTest {
9048 protected:
dchengb03027d2014-10-21 12:00:209049 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:209050 context->set_ssl_config_service(
9051 new TestSSLConfigService(false /* check for EV */,
9052 false /* online revocation checking */,
9053 true /* require rev. checking for local
9054 anchors */));
9055 }
9056};
9057
[email protected]3a86a712013-07-30 07:16:209058TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
9059 if (!SystemSupportsOCSP()) {
9060 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9061 return;
9062 }
9063
9064 if (!SystemSupportsHardFailRevocationChecking()) {
9065 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
9066 << "revocation checking";
9067 return;
9068 }
9069
9070 SpawnedTestServer::SSLOptions ssl_options(
9071 SpawnedTestServer::SSLOptions::CERT_AUTO);
9072 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9073
9074 CertStatus cert_status;
9075 DoConnection(ssl_options, &cert_status);
9076
9077 EXPECT_EQ(CERT_STATUS_REVOKED,
9078 cert_status & CERT_STATUS_REVOKED);
9079
9080 // Without a positive OCSP response, we shouldn't show the EV status.
9081 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9082}
9083
[email protected]a13234c2012-03-20 21:45:029084class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
9085 protected:
dchengb03027d2014-10-21 12:00:209086 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:029087 context->set_ssl_config_service(
9088 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:209089 false /* online revocation checking */,
9090 false /* require rev. checking for local
9091 anchors */));
[email protected]a13234c2012-03-20 21:45:029092 }
9093};
9094
9095TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
9096 if (!SystemSupportsOCSP()) {
9097 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9098 return;
9099 }
9100
[email protected]ce7d0cbc2013-05-03 18:57:229101 SpawnedTestServer::SSLOptions ssl_options(
9102 SpawnedTestServer::SSLOptions::CERT_AUTO);
9103 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029104 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9105
[email protected]924e9f92012-12-16 22:00:539106 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129107 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029108
9109 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9110 cert_status & CERT_STATUS_ALL_ERRORS);
9111
9112 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089113 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9114 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029115}
9116
[email protected]be0fff62013-08-29 23:37:489117TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
9118 if (!SystemSupportsOCSP()) {
9119 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9120 return;
9121 }
9122
9123 SpawnedTestServer::SSLOptions ssl_options(
9124 SpawnedTestServer::SSLOptions::CERT_AUTO);
9125 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9126 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9127
9128 CertStatus cert_status;
9129 DoConnection(ssl_options, &cert_status);
9130
9131 // Currently only works for Windows. When using NSS or OS X, it's not
9132 // possible to determine whether the check failed because of actual
9133 // revocation or because there was an OCSP failure.
9134#if defined(OS_WIN)
9135 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9136#else
9137 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9138#endif
9139
9140 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9141 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9142 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9143}
9144
[email protected]a13234c2012-03-20 21:45:029145TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
9146 if (!SystemSupportsOCSP()) {
9147 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9148 return;
9149 }
9150
[email protected]ce7d0cbc2013-05-03 18:57:229151 SpawnedTestServer::SSLOptions ssl_options(
9152 SpawnedTestServer::SSLOptions::CERT_AUTO);
9153 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:029154 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9155
9156 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129157 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029158
9159 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9160
9161 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9162 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:089163 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9164 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029165}
9166
9167TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
9168 if (!SystemSupportsOCSP()) {
9169 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9170 return;
9171 }
9172
[email protected]ce7d0cbc2013-05-03 18:57:229173 SpawnedTestServer::SSLOptions ssl_options(
9174 SpawnedTestServer::SSLOptions::CERT_AUTO);
9175 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029176 SSLConfigService::SetCRLSet(
9177 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9178
9179 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129180 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029181
9182 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9183 cert_status & CERT_STATUS_ALL_ERRORS);
9184
9185 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089186 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9187 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029188}
9189
[email protected]51523f52013-07-31 21:57:289190TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9191 if (!SystemSupportsOCSP()) {
9192 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9193 return;
9194 }
9195
9196 SpawnedTestServer::SSLOptions ssl_options(
9197 SpawnedTestServer::SSLOptions::CERT_AUTO);
9198 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9199 SSLConfigService::SetCRLSet(
9200 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9201 false, &kOCSPTestCertSPKI, "")));
9202
9203 CertStatus cert_status;
9204 DoConnection(ssl_options, &cert_status);
9205
9206 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9207 // revocation check for EV.
9208 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9209 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9210 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9211 EXPECT_FALSE(
9212 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9213}
9214
9215TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9216 if (!SystemSupportsOCSP()) {
9217 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9218 return;
9219 }
9220
[email protected]ce7d0cbc2013-05-03 18:57:229221 SpawnedTestServer::SSLOptions ssl_options(
9222 SpawnedTestServer::SSLOptions::CERT_AUTO);
9223 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029224 SSLConfigService::SetCRLSet(
9225 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9226
[email protected]51523f52013-07-31 21:57:289227 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129228 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029229
[email protected]51523f52013-07-31 21:57:289230 // Even with a fresh CRLSet, we should still do online revocation checks when
9231 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9232 // test.
9233 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9234 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029235
[email protected]51523f52013-07-31 21:57:289236 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029237 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289238 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029239}
9240
[email protected]b6f2de32012-08-17 04:35:089241TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9242 // Test that when EV verification is requested, but online revocation
9243 // checking is disabled, and the leaf certificate is not in fact EV, that
9244 // no revocation checking actually happens.
9245 if (!SystemSupportsOCSP()) {
9246 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9247 return;
9248 }
9249
9250 // Unmark the certificate's OID as EV, which should disable revocation
9251 // checking (as per the user preference)
9252 ev_test_policy_.reset();
9253
[email protected]ce7d0cbc2013-05-03 18:57:229254 SpawnedTestServer::SSLOptions ssl_options(
9255 SpawnedTestServer::SSLOptions::CERT_AUTO);
9256 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089257 SSLConfigService::SetCRLSet(
9258 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9259
9260 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129261 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:089262
9263 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9264
9265 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9266 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9267}
9268
[email protected]a13234c2012-03-20 21:45:029269class HTTPSCRLSetTest : public HTTPSOCSPTest {
9270 protected:
dchengb03027d2014-10-21 12:00:209271 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:029272 context->set_ssl_config_service(
9273 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:209274 false /* online revocation checking */,
9275 false /* require rev. checking for local
9276 anchors */));
[email protected]a13234c2012-03-20 21:45:029277 }
9278};
9279
9280TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229281 SpawnedTestServer::SSLOptions ssl_options(
9282 SpawnedTestServer::SSLOptions::CERT_AUTO);
9283 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029284 SSLConfigService::SetCRLSet(
9285 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9286
[email protected]924e9f92012-12-16 22:00:539287 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129288 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029289
9290 // If we're not trying EV verification then, even if the CRLSet has expired,
9291 // we don't fall back to online revocation checks.
9292 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9293 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9294 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9295}
[email protected]51523f52013-07-31 21:57:289296
9297TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309298#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289299 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9300 return;
9301#endif
9302
9303 SpawnedTestServer::SSLOptions ssl_options(
9304 SpawnedTestServer::SSLOptions::CERT_AUTO);
9305 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9306 ssl_options.cert_serial = 10;
9307 SSLConfigService::SetCRLSet(
9308 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9309 false, &kOCSPTestCertSPKI, "\x0a")));
9310
9311 CertStatus cert_status = 0;
9312 DoConnection(ssl_options, &cert_status);
9313
9314 // If the certificate is recorded as revoked in the CRLSet, that should be
9315 // reflected without online revocation checking.
9316 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9317 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9318 EXPECT_FALSE(
9319 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9320}
[email protected]316c1e5e2012-09-12 15:17:449321#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279322
mmenke9f2ec60c2015-06-01 20:59:479323#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9324// These tests aren't passing on Android. Either the RemoteTestServer isn't
9325// starting up successfully, or it can't access the test files.
9326// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319327class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119328 public:
[email protected]d9fca99a2012-02-24 16:16:209329 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:479330 : ftp_transaction_factory_(&host_resolver_),
9331 test_server_(SpawnedTestServer::TYPE_FTP,
9332 SpawnedTestServer::kLocalhost,
9333 base::FilePath(kTestFilePath)) {
9334 // Can't use |default_context_|'s HostResolver to set up the
9335 // FTPTransactionFactory because it hasn't been created yet.
9336 default_context_.set_host_resolver(&host_resolver_);
9337 }
9338
9339 // URLRequestTest interface:
9340 void SetUpFactory() override {
9341 // Add FTP support to the default URLRequestContext.
9342 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:209343 "ftp",
9344 make_scoped_ptr(new FtpProtocolHandler(&ftp_transaction_factory_)));
mmenke9f2ec60c2015-06-01 20:59:479345 }
9346
9347 std::string GetTestFileContents() {
9348 base::FilePath path;
9349 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9350 path = path.Append(kTestFilePath);
9351 path = path.AppendASCII(kFtpTestFile);
9352 std::string contents;
9353 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9354 return contents;
[email protected]95409e12010-08-17 20:07:119355 }
9356
[email protected]b89ca032009-08-31 21:41:319357 protected:
mmenke9f2ec60c2015-06-01 20:59:479358 MockHostResolver host_resolver_;
9359 FtpNetworkLayer ftp_transaction_factory_;
9360
[email protected]ce7d0cbc2013-05-03 18:57:229361 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:319362};
9363
[email protected]d2a133182012-08-05 16:44:089364// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099365TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089366 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089367
9368 TestDelegate d;
9369 {
davidben151423e2015-03-23 18:48:369370 scoped_ptr<URLRequest> r(
9371 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199372 r->Start();
9373 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089374
[email protected]255620da2013-08-19 13:14:299375 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089376
[email protected]f7022f32014-08-21 16:32:199377 EXPECT_FALSE(r->is_pending());
9378 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
9379 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:089380 }
9381}
9382
mmenke9f2ec60c2015-06-01 20:59:479383TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:119384 ASSERT_TRUE(test_server_.Start());
9385
[email protected]a25e90e2009-09-09 17:05:379386 TestDelegate d;
9387 {
[email protected]f7022f32014-08-21 16:32:199388 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369389 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199390 r->Start();
9391 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379392
[email protected]255620da2013-08-19 13:14:299393 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379394
[email protected]f7022f32014-08-21 16:32:199395 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379396 EXPECT_EQ(1, d.response_started_count());
9397 EXPECT_FALSE(d.received_data_before_response());
9398 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:199399 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199400 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199401 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199402 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379403 }
9404}
9405
mmenke9f2ec60c2015-06-01 20:59:479406TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:119407 ASSERT_TRUE(test_server_.Start());
9408
[email protected]dd265012009-01-08 20:45:279409 TestDelegate d;
9410 {
[email protected]f7022f32014-08-21 16:32:199411 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479412 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199413 r->Start();
9414 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279415
[email protected]255620da2013-08-19 13:14:299416 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279417
[email protected]f7022f32014-08-21 16:32:199418 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279419 EXPECT_EQ(1, d.response_started_count());
9420 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479421 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:199422 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199423 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199424 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199425 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279426 }
9427}
9428
mmenke9f2ec60c2015-06-01 20:59:479429TEST_F(URLRequestTestFTP, FTPGetTest) {
[email protected]95409e12010-08-17 20:07:119430 ASSERT_TRUE(test_server_.Start());
9431
[email protected]dd265012009-01-08 20:45:279432 TestDelegate d;
9433 {
mmenke9f2ec60c2015-06-01 20:59:479434 scoped_ptr<URLRequest> r(
9435 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9436 kFtpTestFile, "chrome", "chrome"),
9437 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199438 r->Start();
9439 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279440
[email protected]255620da2013-08-19 13:14:299441 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279442
[email protected]f7022f32014-08-21 16:32:199443 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479444 EXPECT_EQ(1, d.response_started_count());
9445 EXPECT_FALSE(d.received_data_before_response());
9446 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:199447 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199448 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199449 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199450 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:259451
9452 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:199453 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:259454 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:279455 }
9456}
9457
mmenke9f2ec60c2015-06-01 20:59:479458TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:119459 ASSERT_TRUE(test_server_.Start());
9460
[email protected]dd265012009-01-08 20:45:279461 TestDelegate d;
9462 {
[email protected]f7022f32014-08-21 16:32:199463 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479464 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199465 "wrong_password"),
davidben151423e2015-03-23 18:48:369466 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199467 r->Start();
9468 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279469
[email protected]255620da2013-08-19 13:14:299470 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279471
[email protected]f7022f32014-08-21 16:32:199472 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279473 EXPECT_EQ(1, d.response_started_count());
9474 EXPECT_FALSE(d.received_data_before_response());
9475 EXPECT_EQ(d.bytes_received(), 0);
9476 }
9477}
9478
mmenke9f2ec60c2015-06-01 20:59:479479TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:119480 ASSERT_TRUE(test_server_.Start());
9481
[email protected]8b8a197d2009-08-26 15:57:589482 TestDelegate d;
9483 // Set correct login credentials. The delegate will be asked for them when
9484 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589485 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589486 {
[email protected]f7022f32014-08-21 16:32:199487 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479488 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199489 "wrong_password"),
davidben151423e2015-03-23 18:48:369490 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199491 r->Start();
9492 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589493
[email protected]255620da2013-08-19 13:14:299494 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589495
[email protected]f7022f32014-08-21 16:32:199496 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589497 EXPECT_EQ(1, d.response_started_count());
9498 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479499 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589500 }
9501}
9502
mmenke9f2ec60c2015-06-01 20:59:479503TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:119504 ASSERT_TRUE(test_server_.Start());
9505
[email protected]dd265012009-01-08 20:45:279506 TestDelegate d;
9507 {
mmenke9f2ec60c2015-06-01 20:59:479508 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9509 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9510 "chrome"),
9511 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199512 r->Start();
9513 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279514
[email protected]255620da2013-08-19 13:14:299515 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279516
[email protected]f7022f32014-08-21 16:32:199517 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279518 EXPECT_EQ(1, d.response_started_count());
9519 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479520 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279521 }
9522}
[email protected]8b8a197d2009-08-26 15:57:589523
mmenke9f2ec60c2015-06-01 20:59:479524TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:119525 ASSERT_TRUE(test_server_.Start());
9526
[email protected]8b8a197d2009-08-26 15:57:589527 TestDelegate d;
9528 // Set correct login credentials. The delegate will be asked for them when
9529 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589530 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589531 {
mmenke9f2ec60c2015-06-01 20:59:479532 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9533 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9534 "chrome"),
9535 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199536 r->Start();
9537 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589538
[email protected]255620da2013-08-19 13:14:299539 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589540
[email protected]f7022f32014-08-21 16:32:199541 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589542 EXPECT_EQ(1, d.response_started_count());
9543 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479544 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589545 }
9546}
[email protected]60a3df52009-09-22 16:13:249547
mmenke9f2ec60c2015-06-01 20:59:479548TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:119549 ASSERT_TRUE(test_server_.Start());
9550
[email protected]60a3df52009-09-22 16:13:249551 scoped_ptr<TestDelegate> d(new TestDelegate);
9552 {
9553 // Pass correct login identity in the URL.
mmenke9f2ec60c2015-06-01 20:59:479554 scoped_ptr<URLRequest> r(
9555 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9556 kFtpTestFile, "chrome", "chrome"),
9557 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199558 r->Start();
9559 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249560
[email protected]255620da2013-08-19 13:14:299561 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249562
[email protected]f7022f32014-08-21 16:32:199563 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249564 EXPECT_EQ(1, d->response_started_count());
9565 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479566 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249567 }
9568
9569 d.reset(new TestDelegate);
9570 {
9571 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199572 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479573 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199574 r->Start();
9575 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249576
[email protected]255620da2013-08-19 13:14:299577 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249578
[email protected]f7022f32014-08-21 16:32:199579 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249580 EXPECT_EQ(1, d->response_started_count());
9581 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479582 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249583 }
9584}
9585
mmenke9f2ec60c2015-06-01 20:59:479586TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:119587 ASSERT_TRUE(test_server_.Start());
9588
[email protected]60a3df52009-09-22 16:13:249589 scoped_ptr<TestDelegate> d(new TestDelegate);
9590 // Set correct login credentials. The delegate will be asked for them when
9591 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589592 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249593 {
[email protected]f7022f32014-08-21 16:32:199594 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479595 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199596 "wrong_password"),
davidben151423e2015-03-23 18:48:369597 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199598 r->Start();
9599 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249600
[email protected]255620da2013-08-19 13:14:299601 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249602
[email protected]f7022f32014-08-21 16:32:199603 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249604 EXPECT_EQ(1, d->response_started_count());
9605 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479606 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249607 }
9608
9609 // Use a new delegate without explicit credentials. The cached ones should be
9610 // used.
9611 d.reset(new TestDelegate);
9612 {
9613 // Don't pass wrong credentials in the URL, they would override valid cached
9614 // ones.
[email protected]f7022f32014-08-21 16:32:199615 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479616 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199617 r->Start();
9618 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249619
[email protected]255620da2013-08-19 13:14:299620 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249621
[email protected]f7022f32014-08-21 16:32:199622 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249623 EXPECT_EQ(1, d->response_started_count());
9624 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479625 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249626 }
9627}
[email protected]316c1e5e2012-09-12 15:17:449628#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519629
ttuttlec0c828492015-05-15 01:25:559630TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9631 TestDelegate d;
9632 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9633 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9634 d.set_quit_on_network_start(true);
9635
9636 EXPECT_FALSE(req->response_info().network_accessed);
9637
9638 req->Start();
9639 base::RunLoop().Run();
9640
9641 EXPECT_EQ(1, d.received_before_network_start_count());
9642 EXPECT_EQ(0, d.response_started_count());
9643 EXPECT_FALSE(req->response_info().network_accessed);
9644
9645 req->ResumeNetworkStart();
9646 base::RunLoop().Run();
9647}
9648
9649TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9650 TestDelegate d;
9651 scoped_ptr<URLRequest> req(
9652 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9653
9654 EXPECT_FALSE(req->response_info().network_accessed);
9655
9656 req->Start();
9657 base::RunLoop().Run();
9658
9659 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9660 EXPECT_FALSE(req->response_info().network_accessed);
9661}
9662
9663TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9664 MockHostResolver host_resolver;
9665 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9666 TestURLRequestContext context(true);
9667 context.set_network_delegate(&network_delegate);
9668 context.set_host_resolver(&host_resolver);
9669 host_resolver.rules()->AddSimulatedFailure("*");
9670 context.Init();
9671
9672 TestDelegate d;
9673 scoped_ptr<URLRequest> req(context.CreateRequest(
9674 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9675
9676 EXPECT_FALSE(req->response_info().network_accessed);
9677
9678 req->Start();
9679 base::RunLoop().Run();
9680 EXPECT_TRUE(req->response_info().network_accessed);
9681}
9682
alexanderkcd904b52015-07-24 18:57:229683// Test that URLRequest is canceled correctly and with detached request
9684// URLRequestRedirectJob does not crash in StartAsync.
9685// See http://crbug.com/508900
9686TEST_F(URLRequestTest, URLRequestRedirectJobDetachRequestNoCrash) {
9687 TestDelegate d;
9688 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9689 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
9690
9691 URLRequestRedirectJob* job = new URLRequestRedirectJob(
9692 req.get(), &default_network_delegate_,
9693 GURL("http://this-should-never-be-navigated-to/"),
9694 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp");
9695 AddTestInterceptor()->set_main_intercept_job(job);
9696
9697 req->Start();
9698 req->Cancel();
9699 job->DetachRequest();
9700 base::RunLoop().RunUntilIdle();
9701 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
9702 EXPECT_EQ(0, d.received_redirect_count());
9703}
9704
[email protected]7461a402011-03-24 23:19:519705} // namespace net