blob: f91a28327846a13bfa213680604dfea1730e45b2 [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"
[email protected]89b32522013-05-07 20:04:2181#include "net/test/spawned_test_server/spawned_test_server.h"
mmenkefb18c772015-09-30 22:22:5082#include "net/test/url_request/url_request_failed_job.h"
[email protected]e0f35c92013-05-08 16:04:3483#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4384#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5285#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:5086#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:1487#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:5088#include "net/url_request/url_request_intercepting_job_factory.h"
89#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:4990#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5191#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4792#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4493#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5294#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1595#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:5296
[email protected]02494ec2014-05-07 15:05:2997#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:5598#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:2999#include "net/url_request/file_protocol_handler.h"
100#include "net/url_request/url_request_file_dir_job.h"
101#endif
102
mmenke9f2ec60c2015-06-01 20:59:47103#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
104#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29105#include "net/url_request/ftp_protocol_handler.h"
106#endif
107
[email protected]dffe8242012-03-20 15:14:27108#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48109#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56110#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27111#include "base/win/windows_version.h"
112#endif
113
[email protected]ad65a3e2013-12-25 18:18:01114using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33115using base::Time;
halton.huoe4e45742014-12-08 07:55:46116using std::string;
[email protected]e1acf6f2008-10-27 20:43:33117
[email protected]7461a402011-03-24 23:19:51118namespace net {
119
initial.commit586acc5fe2008-07-26 22:42:52120namespace {
121
[email protected]42cba2fb2013-03-29 19:58:57122const base::string16 kChrome(ASCIIToUTF16("chrome"));
123const base::string16 kSecret(ASCIIToUTF16("secret"));
124const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44125
mmenke9f2ec60c2015-06-01 20:59:47126const base::FilePath::CharType kTestFilePath[] =
127 FILE_PATH_LITERAL("net/data/url_request_unittest");
128
129#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
130// Test file used in most FTP tests.
131const char kFtpTestFile[] = "BullRunSpeech.txt";
132#endif
133
[email protected]2bba3252013-04-08 19:50:59134// Tests load timing information in the case a fresh connection was used, with
135// no proxy.
[email protected]cba24642014-08-15 20:49:59136void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25137 int connect_timing_flags) {
138 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59139 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25140
141 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
142 EXPECT_FALSE(load_timing_info.request_start.is_null());
143
144 EXPECT_LE(load_timing_info.request_start,
145 load_timing_info.connect_timing.connect_start);
146 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
147 connect_timing_flags);
148 EXPECT_LE(load_timing_info.connect_timing.connect_end,
149 load_timing_info.send_start);
150 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
151 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
152
[email protected]58e32bb2013-01-21 18:23:25153 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
154 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
155}
156
[email protected]2bba3252013-04-08 19:50:59157// Same as above, but with proxy times.
158void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59159 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59160 int connect_timing_flags) {
161 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59162 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59163
164 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
165 EXPECT_FALSE(load_timing_info.request_start.is_null());
166
167 EXPECT_LE(load_timing_info.request_start,
168 load_timing_info.proxy_resolve_start);
169 EXPECT_LE(load_timing_info.proxy_resolve_start,
170 load_timing_info.proxy_resolve_end);
171 EXPECT_LE(load_timing_info.proxy_resolve_end,
172 load_timing_info.connect_timing.connect_start);
173 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
174 connect_timing_flags);
175 EXPECT_LE(load_timing_info.connect_timing.connect_end,
176 load_timing_info.send_start);
177 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
178 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
179}
180
181// Same as above, but with a reused socket and proxy times.
182void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59183 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59184 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59185 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59186
187 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
188 EXPECT_FALSE(load_timing_info.request_start.is_null());
189
190 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
191
192 EXPECT_LE(load_timing_info.request_start,
193 load_timing_info.proxy_resolve_start);
194 EXPECT_LE(load_timing_info.proxy_resolve_start,
195 load_timing_info.proxy_resolve_end);
196 EXPECT_LE(load_timing_info.proxy_resolve_end,
197 load_timing_info.send_start);
198 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
199 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
200}
201
xunjielia6888202015-04-14 21:34:25202#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25203// Tests load timing information in the case of a cache hit, when no cache
204// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17205base::StringPiece TestNetResourceProvider(int key) {
206 return "header";
207}
208
209void FillBuffer(char* buffer, size_t len) {
210 static bool called = false;
211 if (!called) {
212 called = true;
213 int seed = static_cast<int>(Time::Now().ToInternalValue());
214 srand(seed);
215 }
216
217 for (size_t i = 0; i < len; i++) {
218 buffer[i] = static_cast<char>(rand());
219 if (!buffer[i])
220 buffer[i] = 'g';
221 }
222}
xunjielia6888202015-04-14 21:34:25223#endif
[email protected]e3a85452013-11-14 01:46:17224
225#if !defined(OS_IOS)
[email protected]3b23a222013-05-15 21:33:25226void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59227 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25228 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59229 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25230
231 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
232 EXPECT_FALSE(load_timing_info.request_start.is_null());
233
234 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
235 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
236 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
237 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
238
239 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
240 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
241}
242
mmenke9f2ec60c2015-06-01 20:59:47243#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25244// Tests load timing in the case that there is no HTTP response. This can be
245// used to test in the case of errors or non-HTTP requests.
246void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59247 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25248 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59249 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25250
251 // Only the request times should be non-null.
252 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
253 EXPECT_FALSE(load_timing_info.request_start.is_null());
254
255 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
256
257 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
258 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
259 EXPECT_TRUE(load_timing_info.send_start.is_null());
260 EXPECT_TRUE(load_timing_info.send_end.is_null());
261 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
262}
xunjielia6888202015-04-14 21:34:25263#endif
[email protected]58e32bb2013-01-21 18:23:25264
mmenkefb18c772015-09-30 22:22:50265// Test power monitor source that can simulate entering suspend mode. Can't use
266// the one in base/ because it insists on bringing its own MessageLoop.
267class TestPowerMonitorSource : public base::PowerMonitorSource {
268 public:
269 TestPowerMonitorSource() {}
270 ~TestPowerMonitorSource() override {}
271
272 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
273
274 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
275
276 bool IsOnBatteryPowerImpl() override { return false; }
277
278 private:
279 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
280};
281
[email protected]71c64f62008-11-15 04:36:51282// Do a case-insensitive search through |haystack| for |needle|.
283bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50284 std::string::const_iterator it = std::search(
285 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
286 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51287 return it != haystack.end();
288}
289
mmenkecbc2b712014-10-09 20:29:07290scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
[email protected]f288ef02012-12-15 20:28:28291 scoped_ptr<UploadElementReader> reader(
292 new UploadBytesElementReader(data, strlen(data)));
mmenkecbc2b712014-10-09 20:29:07293 return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23294}
295
[email protected]96adadb2010-08-28 01:16:17296// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51297void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17298 // -1 means unknown. 0 means no encryption.
299 EXPECT_GT(ssl_info.security_bits, 0);
300
301 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
pkasting6b68a162014-12-01 22:10:29302 uint16 cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17303 ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29304 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17305}
306
[email protected]79e1fd62013-06-20 06:50:04307void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
308 const GURL& host_url) {
309 std::string sent_value;
310
311 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
312 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
313
314 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
315 EXPECT_EQ("keep-alive", sent_value);
316}
317
[email protected]ede03212012-09-07 12:52:26318bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27319 size_t size = a.size();
320
321 if (size != b.size())
322 return false;
323
324 for (size_t i = 0; i < size; ++i) {
325 if (!a[i].Equals(b[i]))
326 return false;
327 }
328
329 return true;
330}
[email protected]e3a85452013-11-14 01:46:17331#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27332
[email protected]dc5a5cf2012-09-26 02:49:30333// A network delegate that allows the user to choose a subset of request stages
334// to block in. When blocking, the delegate can do one of the following:
335// * synchronously return a pre-specified error code, or
336// * asynchronously return that value via an automatically called callback,
337// or
338// * block and wait for the user to do a callback.
339// Additionally, the user may also specify a redirect URL -- then each request
340// with the current URL different from the redirect target will be redirected
341// to that target, in the on-before-URL-request stage, independent of whether
342// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12343class BlockingNetworkDelegate : public TestNetworkDelegate {
344 public:
[email protected]dc5a5cf2012-09-26 02:49:30345 // Stages in which the delegate can block.
346 enum Stage {
[email protected]9045b8822012-01-13 20:35:35347 NOT_BLOCKED = 0,
348 ON_BEFORE_URL_REQUEST = 1 << 0,
349 ON_BEFORE_SEND_HEADERS = 1 << 1,
350 ON_HEADERS_RECEIVED = 1 << 2,
351 ON_AUTH_REQUIRED = 1 << 3
352 };
353
[email protected]dc5a5cf2012-09-26 02:49:30354 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59355 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30356 enum BlockMode {
357 SYNCHRONOUS, // No callback, returns specified return values.
358 AUTO_CALLBACK, // |this| posts a task to run the callback using the
359 // specified return codes.
360 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
361 // |auth_retval_| are ignored. In every blocking stage the
362 // message loop is quit.
363 };
364
365 // Creates a delegate which does not block at all.
366 explicit BlockingNetworkDelegate(BlockMode block_mode);
367
368 // For users to trigger a callback returning |response|.
369 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
370 // Only call if |block_mode_| == USER_CALLBACK.
371 void DoCallback(int response);
372 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
373
374 // Setters.
375 void set_retval(int retval) {
376 ASSERT_NE(USER_CALLBACK, block_mode_);
377 ASSERT_NE(ERR_IO_PENDING, retval);
378 ASSERT_NE(OK, retval);
379 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35380 }
381
[email protected]dc5a5cf2012-09-26 02:49:30382 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
383 // |auth_credentials_| will be passed with the response.
384 void set_auth_retval(AuthRequiredResponse auth_retval) {
385 ASSERT_NE(USER_CALLBACK, block_mode_);
386 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
387 auth_retval_ = auth_retval;
388 }
389 void set_auth_credentials(const AuthCredentials& auth_credentials) {
390 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35391 }
392
[email protected]dc5a5cf2012-09-26 02:49:30393 void set_redirect_url(const GURL& url) {
394 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35395 }
396
[email protected]dc5a5cf2012-09-26 02:49:30397 void set_block_on(int block_on) {
398 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35399 }
400
[email protected]dc5a5cf2012-09-26 02:49:30401 // Allows the user to check in which state did we block.
402 Stage stage_blocked_for_callback() const {
403 EXPECT_EQ(USER_CALLBACK, block_mode_);
404 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35405 }
406
407 private:
[email protected]dc5a5cf2012-09-26 02:49:30408 void RunCallback(int response, const CompletionCallback& callback);
409 void RunAuthCallback(AuthRequiredResponse response,
410 const AuthCallback& callback);
411
[email protected]9045b8822012-01-13 20:35:35412 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20413 int OnBeforeURLRequest(URLRequest* request,
414 const CompletionCallback& callback,
415 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35416
dchengb03027d2014-10-21 12:00:20417 int OnBeforeSendHeaders(URLRequest* request,
418 const CompletionCallback& callback,
419 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35420
dchengb03027d2014-10-21 12:00:20421 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35422 URLRequest* request,
423 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32424 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16425 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13426 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35427
dchengb03027d2014-10-21 12:00:20428 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35429 URLRequest* request,
430 const AuthChallengeInfo& auth_info,
431 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13432 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35433
[email protected]dc5a5cf2012-09-26 02:49:30434 // Resets the callbacks and |stage_blocked_for_callback_|.
435 void Reset();
[email protected]9045b8822012-01-13 20:35:35436
[email protected]dc5a5cf2012-09-26 02:49:30437 // Checks whether we should block in |stage|. If yes, returns an error code
438 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
439 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
440
441 // Configuration parameters, can be adjusted by public methods:
442 const BlockMode block_mode_;
443
444 // Values returned on blocking stages when mode is SYNCHRONOUS or
445 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
446 int retval_; // To be returned in non-auth stages.
447 AuthRequiredResponse auth_retval_;
448
[email protected]5f714132014-03-26 10:41:16449 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30450 int block_on_; // Bit mask: in which stages to block.
451
452 // |auth_credentials_| will be copied to |*target_auth_credential_| on
453 // callback.
454 AuthCredentials auth_credentials_;
455 AuthCredentials* target_auth_credentials_;
456
457 // Internal variables, not set by not the user:
458 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
459 // USER_CALLBACK).
460 Stage stage_blocked_for_callback_;
461
462 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35463 CompletionCallback callback_;
464 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30465
466 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
467
468 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35469};
470
[email protected]dc5a5cf2012-09-26 02:49:30471BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
472 : block_mode_(block_mode),
473 retval_(OK),
474 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
475 block_on_(0),
476 target_auth_credentials_(NULL),
477 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32478 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30479}
480
481void BlockingNetworkDelegate::DoCallback(int response) {
482 ASSERT_EQ(USER_CALLBACK, block_mode_);
483 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
484 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
485 CompletionCallback callback = callback_;
486 Reset();
487 RunCallback(response, callback);
488}
489
490void BlockingNetworkDelegate::DoAuthCallback(
491 NetworkDelegate::AuthRequiredResponse response) {
492 ASSERT_EQ(USER_CALLBACK, block_mode_);
493 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
494 AuthCallback auth_callback = auth_callback_;
495 Reset();
496 RunAuthCallback(response, auth_callback);
497}
498
499void BlockingNetworkDelegate::RunCallback(int response,
500 const CompletionCallback& callback) {
501 callback.Run(response);
502}
503
504void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
505 const AuthCallback& callback) {
506 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
507 ASSERT_TRUE(target_auth_credentials_ != NULL);
508 *target_auth_credentials_ = auth_credentials_;
509 }
510 callback.Run(response);
511}
512
513int BlockingNetworkDelegate::OnBeforeURLRequest(
514 URLRequest* request,
515 const CompletionCallback& callback,
516 GURL* new_url) {
517 if (redirect_url_ == request->url())
518 return OK; // We've already seen this request and redirected elsewhere.
519
520 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
521
522 if (!redirect_url_.is_empty())
523 *new_url = redirect_url_;
524
525 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
526}
527
528int BlockingNetworkDelegate::OnBeforeSendHeaders(
529 URLRequest* request,
530 const CompletionCallback& callback,
531 HttpRequestHeaders* headers) {
532 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
533
534 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
535}
536
537int BlockingNetworkDelegate::OnHeadersReceived(
538 URLRequest* request,
539 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32540 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16541 scoped_refptr<HttpResponseHeaders>* override_response_headers,
542 GURL* allowed_unsafe_redirect_url) {
543 TestNetworkDelegate::OnHeadersReceived(request,
544 callback,
545 original_response_headers,
546 override_response_headers,
547 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30548
549 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
550}
551
552NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
553 URLRequest* request,
554 const AuthChallengeInfo& auth_info,
555 const AuthCallback& callback,
556 AuthCredentials* credentials) {
557 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
558 credentials);
559 // Check that the user has provided callback for the previous blocked stage.
560 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
561
562 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
563 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
564 }
565
566 target_auth_credentials_ = credentials;
567
568 switch (block_mode_) {
569 case SYNCHRONOUS:
570 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
571 *target_auth_credentials_ = auth_credentials_;
572 return auth_retval_;
573
574 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45575 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30576 FROM_HERE,
577 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
578 weak_factory_.GetWeakPtr(), auth_retval_, callback));
579 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
580
581 case USER_CALLBACK:
582 auth_callback_ = callback;
583 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45584 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17585 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30586 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
587 }
588 NOTREACHED();
589 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
590}
591
592void BlockingNetworkDelegate::Reset() {
593 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
594 stage_blocked_for_callback_ = NOT_BLOCKED;
595 callback_.Reset();
596 auth_callback_.Reset();
597}
598
599int BlockingNetworkDelegate::MaybeBlockStage(
600 BlockingNetworkDelegate::Stage stage,
601 const CompletionCallback& callback) {
602 // Check that the user has provided callback for the previous blocked stage.
603 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
604
605 if ((block_on_ & stage) == 0) {
606 return OK;
607 }
608
609 switch (block_mode_) {
610 case SYNCHRONOUS:
611 EXPECT_NE(OK, retval_);
612 return retval_;
613
614 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45615 base::ThreadTaskRunnerHandle::Get()->PostTask(
616 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
617 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30618 return ERR_IO_PENDING;
619
620 case USER_CALLBACK:
621 callback_ = callback;
622 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45623 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17624 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30625 return ERR_IO_PENDING;
626 }
627 NOTREACHED();
628 return 0;
629}
630
[email protected]d5a4dd62012-05-23 01:41:04631class TestURLRequestContextWithProxy : public TestURLRequestContext {
632 public:
633 // Does not own |delegate|.
634 TestURLRequestContextWithProxy(const std::string& proxy,
635 NetworkDelegate* delegate)
636 : TestURLRequestContext(true) {
637 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
638 set_network_delegate(delegate);
639 Init();
640 }
dchengb03027d2014-10-21 12:00:20641 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04642};
643
estark06e0dac2015-08-07 21:56:01644// A mock ReportSender that just remembers the latest report
645// URI and report to be sent.
646class MockCertificateReportSender
647 : public TransportSecurityState::ReportSender {
648 public:
649 MockCertificateReportSender() {}
650 ~MockCertificateReportSender() override {}
651
652 void Send(const GURL& report_uri, const std::string& report) override {
653 latest_report_uri_ = report_uri;
654 latest_report_ = report;
655 }
656
657 const GURL& latest_report_uri() { return latest_report_uri_; }
658 const std::string& latest_report() { return latest_report_; }
659
660 private:
661 GURL latest_report_uri_;
662 std::string latest_report_;
663};
664
[email protected]d5a4dd62012-05-23 01:41:04665} // namespace
666
[email protected]a592c0432012-12-01 18:10:29667// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48668class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00669 public:
[email protected]ef2bf422012-05-11 03:27:09670 URLRequestTest() : default_context_(true) {
671 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25672 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50673 job_factory_impl_ = new URLRequestJobFactoryImpl();
674 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50675 }
bengr1bf8e942014-11-07 01:36:50676
dcheng67be2b1f2014-10-27 21:47:29677 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18678 // URLRequestJobs may post clean-up tasks on destruction.
679 base::RunLoop().RunUntilIdle();
680 }
[email protected]87a09a92011-07-14 15:50:50681
dcheng2339883c2014-12-23 00:23:05682 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50683 SetUpFactory();
684 default_context_.set_job_factory(job_factory_.get());
685 default_context_.Init();
686 PlatformTest::SetUp();
687 }
688
689 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20690 job_factory_impl_->SetProtocolHandler(
691 "data", make_scoped_ptr(new DataProtocolHandler));
bengr1bf8e942014-11-07 01:36:50692#if !defined(DISABLE_FILE_SUPPORT)
693 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:20694 "file", make_scoped_ptr(new FileProtocolHandler(
695 base::ThreadTaskRunnerHandle::Get())));
bengr1bf8e942014-11-07 01:36:50696#endif
697 }
698
699 TestNetworkDelegate* default_network_delegate() {
700 return &default_network_delegate_;
701 }
702
703 const TestURLRequestContext& default_context() const {
704 return default_context_;
705 }
706
707
[email protected]3c5ca8c2011-09-29 01:14:51708 // Adds the TestJobInterceptor to the default context.
709 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23710 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20711 job_factory_impl_->SetProtocolHandler("http", nullptr);
712 job_factory_impl_->SetProtocolHandler("http",
713 make_scoped_ptr(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23714 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51715 }
716
[email protected]87a09a92011-07-14 15:50:50717 protected:
vishal.b62985ca92015-04-17 08:45:51718 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24719 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50720 URLRequestJobFactoryImpl* job_factory_impl_;
721 scoped_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09722 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48723};
724
[email protected]316c1e5e2012-09-12 15:17:44725TEST_F(URLRequestTest, AboutBlankTest) {
726 TestDelegate d;
727 {
[email protected]f7022f32014-08-21 16:32:19728 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36729 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44730
[email protected]f7022f32014-08-21 16:32:19731 r->Start();
732 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44733
[email protected]255620da2013-08-19 13:14:29734 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44735
[email protected]f7022f32014-08-21 16:32:19736 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44737 EXPECT_FALSE(d.received_data_before_response());
738 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19739 EXPECT_EQ("", r->GetSocketAddress().host());
740 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04741
742 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19743 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44744 }
745}
746
747TEST_F(URLRequestTest, DataURLImageTest) {
748 TestDelegate d;
749 {
750 // Use our nice little Chrome logo.
[email protected]f7022f32014-08-21 16:32:19751 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:19752 GURL(
davidben151423e2015-03-23 18:48:36753 "data:image/png;base64,"
754 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
755 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
756 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
757 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
758 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
759 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
760 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
761 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
762 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
763 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
764 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
765 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
766 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
767 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
768 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
769 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
770 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
771 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
772 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
773 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44774
[email protected]f7022f32014-08-21 16:32:19775 r->Start();
776 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44777
[email protected]255620da2013-08-19 13:14:29778 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44779
[email protected]f7022f32014-08-21 16:32:19780 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44781 EXPECT_FALSE(d.received_data_before_response());
782 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19783 EXPECT_EQ("", r->GetSocketAddress().host());
784 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04785
786 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19787 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44788 }
789}
790
[email protected]5ecf7cb282014-05-11 01:49:55791#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44792TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15793 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44794 PathService::Get(base::FILE_EXE, &app_path);
795 GURL app_url = FilePathToFileURL(app_path);
796
797 TestDelegate d;
798 {
davidben151423e2015-03-23 18:48:36799 scoped_ptr<URLRequest> r(
800 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44801
[email protected]f7022f32014-08-21 16:32:19802 r->Start();
803 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44804
[email protected]255620da2013-08-19 13:14:29805 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44806
807 int64 file_size = -1;
[email protected]56285702013-12-04 18:22:49808 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44809
[email protected]f7022f32014-08-21 16:32:19810 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44811 EXPECT_EQ(1, d.response_started_count());
812 EXPECT_FALSE(d.received_data_before_response());
813 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19814 EXPECT_EQ("", r->GetSocketAddress().host());
815 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04816
817 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19818 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44819 }
820}
821
[email protected]ba40bb762012-12-17 07:11:04822TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15823 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04824 PathService::Get(base::FILE_EXE, &app_path);
825 GURL app_url = FilePathToFileURL(app_path);
826
827 TestDelegate d;
828 {
davidben151423e2015-03-23 18:48:36829 scoped_ptr<URLRequest> r(
830 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04831
[email protected]f7022f32014-08-21 16:32:19832 r->Start();
833 EXPECT_TRUE(r->is_pending());
834 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04835 }
[email protected]79e1fd62013-06-20 06:50:04836 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04837 // destroyed.
[email protected]255620da2013-08-19 13:14:29838 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04839}
840
[email protected]316c1e5e2012-09-12 15:17:44841TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
842 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17843 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44844 FillBuffer(buffer.get(), buffer_size);
845
[email protected]6cdfd7f2013-02-08 20:40:15846 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52847 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44848 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30849 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44850
851 int64 file_size;
[email protected]56285702013-12-04 18:22:49852 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44853
854 const size_t first_byte_position = 500;
855 const size_t last_byte_position = buffer_size - first_byte_position;
856 const size_t content_length = last_byte_position - first_byte_position + 1;
857 std::string partial_buffer_string(buffer.get() + first_byte_position,
858 buffer.get() + last_byte_position + 1);
859
860 TestDelegate d;
861 {
davidben151423e2015-03-23 18:48:36862 scoped_ptr<URLRequest> r(
863 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44864
865 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38866 headers.SetHeader(
867 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59868 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38869 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19870 r->SetExtraRequestHeaders(headers);
871 r->Start();
872 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44873
[email protected]255620da2013-08-19 13:14:29874 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19875 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44876 EXPECT_EQ(1, d.response_started_count());
877 EXPECT_FALSE(d.received_data_before_response());
878 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
879 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
880 EXPECT_TRUE(partial_buffer_string == d.data_received());
881 }
882
[email protected]dd3aa792013-07-16 19:10:23883 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44884}
885
886TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
887 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17888 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44889 FillBuffer(buffer.get(), buffer_size);
890
[email protected]6cdfd7f2013-02-08 20:40:15891 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52892 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44893 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30894 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44895
896 int64 file_size;
[email protected]56285702013-12-04 18:22:49897 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44898
899 const size_t first_byte_position = 500;
900 const size_t last_byte_position = buffer_size - 1;
901 const size_t content_length = last_byte_position - first_byte_position + 1;
902 std::string partial_buffer_string(buffer.get() + first_byte_position,
903 buffer.get() + last_byte_position + 1);
904
905 TestDelegate d;
906 {
davidben151423e2015-03-23 18:48:36907 scoped_ptr<URLRequest> r(
908 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44909
910 HttpRequestHeaders headers;
911 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59912 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38913 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19914 r->SetExtraRequestHeaders(headers);
915 r->Start();
916 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44917
[email protected]255620da2013-08-19 13:14:29918 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19919 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44920 EXPECT_EQ(1, d.response_started_count());
921 EXPECT_FALSE(d.received_data_before_response());
922 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
923 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
924 EXPECT_TRUE(partial_buffer_string == d.data_received());
925 }
926
[email protected]dd3aa792013-07-16 19:10:23927 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44928}
929
930TEST_F(URLRequestTest, FileTestMultipleRanges) {
931 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17932 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44933 FillBuffer(buffer.get(), buffer_size);
934
[email protected]6cdfd7f2013-02-08 20:40:15935 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52936 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44937 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30938 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44939
940 int64 file_size;
[email protected]56285702013-12-04 18:22:49941 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44942
943 TestDelegate d;
944 {
davidben151423e2015-03-23 18:48:36945 scoped_ptr<URLRequest> r(
946 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44947
948 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38949 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19950 r->SetExtraRequestHeaders(headers);
951 r->Start();
952 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44953
[email protected]255620da2013-08-19 13:14:29954 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44955 EXPECT_TRUE(d.request_failed());
956 }
957
[email protected]dd3aa792013-07-16 19:10:23958 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44959}
960
[email protected]3ca8b362013-11-11 22:18:07961TEST_F(URLRequestTest, AllowFileURLs) {
962 base::ScopedTempDir temp_dir;
963 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
964 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52965 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07966 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:30967 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:59968 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:07969
970 {
971 TestDelegate d;
972 TestNetworkDelegate network_delegate;
973 network_delegate.set_can_access_files(true);
974 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36975 scoped_ptr<URLRequest> r(
976 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19977 r->Start();
[email protected]3ca8b362013-11-11 22:18:07978 base::RunLoop().Run();
979 EXPECT_FALSE(d.request_failed());
980 EXPECT_EQ(test_data, d.data_received());
981 }
982
983 {
984 TestDelegate d;
985 TestNetworkDelegate network_delegate;
986 network_delegate.set_can_access_files(false);
987 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36988 scoped_ptr<URLRequest> r(
989 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19990 r->Start();
[email protected]3ca8b362013-11-11 22:18:07991 base::RunLoop().Run();
992 EXPECT_TRUE(d.request_failed());
993 EXPECT_EQ("", d.data_received());
994 }
995}
996
[email protected]316c1e5e2012-09-12 15:17:44997
998TEST_F(URLRequestTest, FileDirCancelTest) {
999 // Put in mock resource provider.
1000 NetModule::SetResourceProvider(TestNetResourceProvider);
1001
1002 TestDelegate d;
1003 {
[email protected]6cdfd7f2013-02-08 20:40:151004 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441005 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1006 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1007 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1008
[email protected]f7022f32014-08-21 16:32:191009 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361010 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191011 req->Start();
1012 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441013
1014 d.set_cancel_in_received_data_pending(true);
1015
[email protected]255620da2013-08-19 13:14:291016 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441017 }
1018
1019 // Take out mock resource provider.
1020 NetModule::SetResourceProvider(NULL);
1021}
1022
[email protected]5f9581402013-10-30 13:08:321023TEST_F(URLRequestTest, FileDirOutputSanity) {
1024 // Verify the general sanity of the the output of the file:
1025 // directory lister by checking for the output of a known existing
1026 // file.
1027 const char sentinel_name[] = "filedir-sentinel";
1028
1029 base::FilePath path;
1030 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471031 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321032
1033 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191034 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361035 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191036 req->Start();
[email protected]5f9581402013-10-30 13:08:321037 base::RunLoop().Run();
1038
1039 // Generate entry for the sentinel file.
1040 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581041 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491042 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321043 EXPECT_GT(info.size, 0);
1044 std::string sentinel_output = GetDirectoryListingEntry(
1045 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1046 std::string(sentinel_name),
1047 false /* is_dir */,
1048 info.size,
1049 info.last_modified);
1050
1051 ASSERT_LT(0, d.bytes_received());
1052 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191053 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:321054 // Check for the entry generated for the "sentinel" file.
1055 const std::string& data = d.data_received();
1056 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1057}
1058
[email protected]316c1e5e2012-09-12 15:17:441059TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1060 // There is an implicit redirect when loading a file path that matches a
1061 // directory and does not end with a slash. Ensure that following such
1062 // redirects does not crash. See http://crbug.com/18686.
1063
[email protected]6cdfd7f2013-02-08 20:40:151064 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441065 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471066 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441067
1068 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191069 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361070 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191071 req->Start();
[email protected]255620da2013-08-19 13:14:291072 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441073
1074 ASSERT_EQ(1, d.received_redirect_count());
1075 ASSERT_LT(0, d.bytes_received());
1076 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191077 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441078}
1079
1080#if defined(OS_WIN)
1081// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1082TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1083 TestDelegate d;
davidben151423e2015-03-23 18:48:361084 scoped_ptr<URLRequest> req(
1085 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191086 req->Start();
[email protected]255620da2013-08-19 13:14:291087 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441088
1089 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191090 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441091}
[email protected]5ecf7cb282014-05-11 01:49:551092#endif // defined(OS_WIN)
1093
1094#endif // !defined(DISABLE_FILE_SUPPORT)
1095
1096TEST_F(URLRequestTest, InvalidUrlTest) {
1097 TestDelegate d;
1098 {
[email protected]f7022f32014-08-21 16:32:191099 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361100 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551101
[email protected]f7022f32014-08-21 16:32:191102 r->Start();
1103 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551104
1105 base::RunLoop().Run();
1106 EXPECT_TRUE(d.request_failed());
1107 }
1108}
1109
jochen0e3b3a62014-09-16 18:31:231110TEST_F(URLRequestTest, InvalidReferrerTest) {
1111 TestURLRequestContext context;
1112 TestNetworkDelegate network_delegate;
1113 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1114 context.set_network_delegate(&network_delegate);
1115 TestDelegate d;
davidben151423e2015-03-23 18:48:361116 scoped_ptr<URLRequest> req(
1117 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231118 req->SetReferrer("https://somewhere.com/");
1119
1120 req->Start();
1121 base::RunLoop().Run();
1122 EXPECT_TRUE(d.request_failed());
1123}
1124
[email protected]5ecf7cb282014-05-11 01:49:551125#if defined(OS_WIN)
1126TEST_F(URLRequestTest, ResolveShortcutTest) {
1127 base::FilePath app_path;
1128 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471129 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551130 app_path = app_path.AppendASCII("with-headers.html");
1131
1132 std::wstring lnk_path = app_path.value() + L".lnk";
1133
1134 base::win::ScopedCOMInitializer com_initializer;
1135
1136 // Temporarily create a shortcut for test
1137 {
1138 base::win::ScopedComPtr<IShellLink> shell;
1139 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1140 CLSCTX_INPROC_SERVER)));
1141 base::win::ScopedComPtr<IPersistFile> persist;
1142 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1143 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1144 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1145 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1146 }
1147
1148 TestDelegate d;
1149 {
[email protected]f7022f32014-08-21 16:32:191150 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361151 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551152
[email protected]f7022f32014-08-21 16:32:191153 r->Start();
1154 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551155
1156 base::RunLoop().Run();
1157
1158 WIN32_FILE_ATTRIBUTE_DATA data;
1159 GetFileAttributesEx(app_path.value().c_str(),
1160 GetFileExInfoStandard, &data);
1161 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1162 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1163 FILE_ATTRIBUTE_NORMAL, NULL);
1164 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1165 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1166 DWORD read_size;
1167 BOOL result;
1168 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1169 &read_size, NULL);
1170 std::string content(buffer.get(), read_size);
1171 CloseHandle(file);
1172
[email protected]f7022f32014-08-21 16:32:191173 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551174 EXPECT_EQ(1, d.received_redirect_count());
1175 EXPECT_EQ(content, d.data_received());
1176 }
1177
1178 // Clean the shortcut
1179 DeleteFile(lnk_path.c_str());
1180}
1181#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441182
1183// Custom URLRequestJobs for use with interceptor tests
1184class RestartTestJob : public URLRequestTestJob {
1185 public:
1186 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1187 : URLRequestTestJob(request, network_delegate, true) {}
1188 protected:
dchengb03027d2014-10-21 12:00:201189 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441190 private:
dchengb03027d2014-10-21 12:00:201191 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441192};
1193
1194class CancelTestJob : public URLRequestTestJob {
1195 public:
1196 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1197 : URLRequestTestJob(request, network_delegate, true) {}
1198 protected:
dchengb03027d2014-10-21 12:00:201199 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441200 private:
dchengb03027d2014-10-21 12:00:201201 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441202};
1203
1204class CancelThenRestartTestJob : public URLRequestTestJob {
1205 public:
1206 explicit CancelThenRestartTestJob(URLRequest* request,
1207 NetworkDelegate* network_delegate)
1208 : URLRequestTestJob(request, network_delegate, true) {
1209 }
1210 protected:
dchengb03027d2014-10-21 12:00:201211 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441212 request_->Cancel();
1213 this->NotifyRestartRequired();
1214 }
1215 private:
dchengb03027d2014-10-21 12:00:201216 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441217};
1218
bengr1bf8e942014-11-07 01:36:501219// An Interceptor for use with interceptor tests.
1220class MockURLRequestInterceptor : public URLRequestInterceptor {
1221 public:
1222 // Static getters for canned response header and data strings.
1223 static std::string ok_data() {
1224 return URLRequestTestJob::test_data_1();
1225 }
1226
1227 static std::string ok_headers() {
1228 return URLRequestTestJob::test_headers();
1229 }
1230
1231 static std::string redirect_data() {
1232 return std::string();
1233 }
1234
1235 static std::string redirect_headers() {
1236 return URLRequestTestJob::test_redirect_headers();
1237 }
1238
1239 static std::string error_data() {
1240 return std::string("ohhh nooooo mr. bill!");
1241 }
1242
1243 static std::string error_headers() {
1244 return URLRequestTestJob::test_error_headers();
1245 }
1246
1247 MockURLRequestInterceptor()
1248 : intercept_main_request_(false), restart_main_request_(false),
1249 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1250 simulate_main_network_error_(false),
1251 intercept_redirect_(false), cancel_redirect_request_(false),
1252 intercept_final_response_(false), cancel_final_request_(false),
1253 use_url_request_http_job_(false),
1254 did_intercept_main_(false), did_restart_main_(false),
1255 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1256 did_simulate_error_main_(false),
1257 did_intercept_redirect_(false), did_cancel_redirect_(false),
1258 did_intercept_final_(false), did_cancel_final_(false) {
1259 }
1260
1261 ~MockURLRequestInterceptor() override {
1262 }
1263
1264 // URLRequestInterceptor implementation:
1265 URLRequestJob* MaybeInterceptRequest(
1266 URLRequest* request,
1267 NetworkDelegate* network_delegate) const override {
1268 if (restart_main_request_) {
1269 restart_main_request_ = false;
1270 did_restart_main_ = true;
1271 return new RestartTestJob(request, network_delegate);
1272 }
1273 if (cancel_main_request_) {
1274 cancel_main_request_ = false;
1275 did_cancel_main_ = true;
1276 return new CancelTestJob(request, network_delegate);
1277 }
1278 if (cancel_then_restart_main_request_) {
1279 cancel_then_restart_main_request_ = false;
1280 did_cancel_then_restart_main_ = true;
1281 return new CancelThenRestartTestJob(request, network_delegate);
1282 }
1283 if (simulate_main_network_error_) {
1284 simulate_main_network_error_ = false;
1285 did_simulate_error_main_ = true;
1286 if (use_url_request_http_job_) {
1287 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1288 }
1289 // This job will result in error since the requested URL is not one of the
1290 // URLs supported by these tests.
1291 return new URLRequestTestJob(request, network_delegate, true);
1292 }
1293 if (!intercept_main_request_)
1294 return nullptr;
1295 intercept_main_request_ = false;
1296 did_intercept_main_ = true;
1297 URLRequestTestJob* job = new URLRequestTestJob(request,
1298 network_delegate,
1299 main_headers_,
1300 main_data_,
1301 true);
1302 job->set_load_timing_info(main_request_load_timing_info_);
1303 return job;
1304 }
1305
1306 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1307 NetworkDelegate* network_delegate,
1308 const GURL& location) const override {
1309 if (cancel_redirect_request_) {
1310 cancel_redirect_request_ = false;
1311 did_cancel_redirect_ = true;
1312 return new CancelTestJob(request, network_delegate);
1313 }
1314 if (!intercept_redirect_)
1315 return nullptr;
1316 intercept_redirect_ = false;
1317 did_intercept_redirect_ = true;
1318 if (use_url_request_http_job_) {
1319 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1320 }
1321 return new URLRequestTestJob(request,
1322 network_delegate,
1323 redirect_headers_,
1324 redirect_data_,
1325 true);
1326 }
1327
1328 URLRequestJob* MaybeInterceptResponse(
1329 URLRequest* request,
1330 NetworkDelegate* network_delegate) const override {
1331 if (cancel_final_request_) {
1332 cancel_final_request_ = false;
1333 did_cancel_final_ = true;
1334 return new CancelTestJob(request, network_delegate);
1335 }
1336 if (!intercept_final_response_)
1337 return nullptr;
1338 intercept_final_response_ = false;
1339 did_intercept_final_ = true;
1340 if (use_url_request_http_job_) {
1341 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1342 }
1343 return new URLRequestTestJob(request,
1344 network_delegate,
1345 final_headers_,
1346 final_data_,
1347 true);
1348 }
1349
1350 void set_intercept_main_request(bool intercept_main_request) {
1351 intercept_main_request_ = intercept_main_request;
1352 }
1353
1354 void set_main_headers(const std::string& main_headers) {
1355 main_headers_ = main_headers;
1356 }
1357
1358 void set_main_data(const std::string& main_data) {
1359 main_data_ = main_data;
1360 }
1361
1362 void set_main_request_load_timing_info(
1363 const LoadTimingInfo& main_request_load_timing_info) {
1364 main_request_load_timing_info_ = main_request_load_timing_info;
1365 }
1366
1367 void set_restart_main_request(bool restart_main_request) {
1368 restart_main_request_ = restart_main_request;
1369 }
1370
1371 void set_cancel_main_request(bool cancel_main_request) {
1372 cancel_main_request_ = cancel_main_request;
1373 }
1374
1375 void set_cancel_then_restart_main_request(
1376 bool cancel_then_restart_main_request) {
1377 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1378 }
1379
1380 void set_simulate_main_network_error(bool simulate_main_network_error) {
1381 simulate_main_network_error_ = simulate_main_network_error;
1382 }
1383
1384 void set_intercept_redirect(bool intercept_redirect) {
1385 intercept_redirect_ = intercept_redirect;
1386 }
1387
1388 void set_redirect_headers(const std::string& redirect_headers) {
1389 redirect_headers_ = redirect_headers;
1390 }
1391
1392 void set_redirect_data(const std::string& redirect_data) {
1393 redirect_data_ = redirect_data;
1394 }
1395
1396 void set_cancel_redirect_request(bool cancel_redirect_request) {
1397 cancel_redirect_request_ = cancel_redirect_request;
1398 }
1399
1400 void set_intercept_final_response(bool intercept_final_response) {
1401 intercept_final_response_ = intercept_final_response;
1402 }
1403
1404 void set_final_headers(const std::string& final_headers) {
1405 final_headers_ = final_headers;
1406 }
1407
1408 void set_final_data(const std::string& final_data) {
1409 final_data_ = final_data;
1410 }
1411
1412 void set_cancel_final_request(bool cancel_final_request) {
1413 cancel_final_request_ = cancel_final_request;
1414 }
1415
1416 void set_use_url_request_http_job(bool use_url_request_http_job) {
1417 use_url_request_http_job_ = use_url_request_http_job;
1418 }
1419
1420 bool did_intercept_main() const {
1421 return did_intercept_main_;
1422 }
1423
1424 bool did_restart_main() const {
1425 return did_restart_main_;
1426 }
1427
1428 bool did_cancel_main() const {
1429 return did_cancel_main_;
1430 }
1431
1432 bool did_cancel_then_restart_main() const {
1433 return did_cancel_then_restart_main_;
1434 }
1435
1436 bool did_simulate_error_main() const {
1437 return did_simulate_error_main_;
1438 }
1439
1440 bool did_intercept_redirect() const {
1441 return did_intercept_redirect_;
1442 }
1443
1444 bool did_cancel_redirect() const {
1445 return did_cancel_redirect_;
1446 }
1447
1448 bool did_intercept_final() const {
1449 return did_intercept_final_;
1450 }
1451
1452 bool did_cancel_final() const {
1453 return did_cancel_final_;
1454 }
1455
1456 private:
1457 // Indicate whether to intercept the main request, and if so specify the
1458 // response to return and the LoadTimingInfo to use.
1459 mutable bool intercept_main_request_;
1460 mutable std::string main_headers_;
1461 mutable std::string main_data_;
1462 mutable LoadTimingInfo main_request_load_timing_info_;
1463
1464 // These indicate actions that can be taken within MaybeInterceptRequest.
1465 mutable bool restart_main_request_;
1466 mutable bool cancel_main_request_;
1467 mutable bool cancel_then_restart_main_request_;
1468 mutable bool simulate_main_network_error_;
1469
1470 // Indicate whether to intercept redirects, and if so specify the response to
1471 // return.
1472 mutable bool intercept_redirect_;
1473 mutable std::string redirect_headers_;
1474 mutable std::string redirect_data_;
1475
1476 // Cancel the request within MaybeInterceptRedirect.
1477 mutable bool cancel_redirect_request_;
1478
1479 // Indicate whether to intercept the final response, and if so specify the
1480 // response to return.
1481 mutable bool intercept_final_response_;
1482 mutable std::string final_headers_;
1483 mutable std::string final_data_;
1484
1485 // Cancel the final request within MaybeInterceptResponse.
1486 mutable bool cancel_final_request_;
1487
1488 // Instruct the interceptor to use a real URLRequestHTTPJob.
1489 mutable bool use_url_request_http_job_;
1490
1491 // These indicate if the interceptor did something or not.
1492 mutable bool did_intercept_main_;
1493 mutable bool did_restart_main_;
1494 mutable bool did_cancel_main_;
1495 mutable bool did_cancel_then_restart_main_;
1496 mutable bool did_simulate_error_main_;
1497 mutable bool did_intercept_redirect_;
1498 mutable bool did_cancel_redirect_;
1499 mutable bool did_intercept_final_;
1500 mutable bool did_cancel_final_;
1501};
1502
1503// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1504class URLRequestInterceptorTest : public URLRequestTest {
1505 public:
1506 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1507 }
1508
1509 ~URLRequestInterceptorTest() override {
1510 // URLRequestJobs may post clean-up tasks on destruction.
1511 base::RunLoop().RunUntilIdle();
1512 }
1513
1514 void SetUpFactory() override {
1515 interceptor_ = new MockURLRequestInterceptor();
1516 job_factory_.reset(new URLRequestInterceptingJobFactory(
1517 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1518 }
1519
1520 MockURLRequestInterceptor* interceptor() const {
1521 return interceptor_;
1522 }
1523
1524 private:
1525 MockURLRequestInterceptor* interceptor_;
1526};
1527
1528TEST_F(URLRequestInterceptorTest, Intercept) {
1529 // Intercept the main request and respond with a simple response.
1530 interceptor()->set_intercept_main_request(true);
1531 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1532 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591533 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501534 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361535 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501536 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1537 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1538 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1539 req->SetUserData(nullptr, user_data0);
1540 req->SetUserData(&user_data1, user_data1);
1541 req->SetUserData(&user_data2, user_data2);
1542 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191543 req->Start();
[email protected]255620da2013-08-19 13:14:291544 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591545
bengr1bf8e942014-11-07 01:36:501546 // Make sure we can retrieve our specific user data.
1547 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1548 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1549 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591550
bengr1bf8e942014-11-07 01:36:501551 // Check that we got one good response.
1552 EXPECT_TRUE(req->status().is_success());
1553 EXPECT_EQ(200, req->response_headers()->response_code());
1554 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1555 EXPECT_EQ(1, d.response_started_count());
1556 EXPECT_EQ(0, d.received_redirect_count());
1557}
[email protected]2bba3252013-04-08 19:50:591558
bengr1bf8e942014-11-07 01:36:501559TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1560 // Intercept the main request and respond with a redirect.
1561 interceptor()->set_intercept_main_request(true);
1562 interceptor()->set_main_headers(
1563 MockURLRequestInterceptor::redirect_headers());
1564 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1565
1566 // Intercept that redirect and respond with a final OK response.
1567 interceptor()->set_intercept_redirect(true);
1568 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1569 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1570
1571 TestDelegate d;
1572 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361573 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501574 req->set_method("GET");
1575 req->Start();
1576 base::RunLoop().Run();
1577
1578 // Check that the interceptor got called as expected.
1579 EXPECT_TRUE(interceptor()->did_intercept_main());
1580 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1581
1582 // Check that we got one good response.
1583 EXPECT_TRUE(req->status().is_success());
1584 if (req->status().is_success())
1585 EXPECT_EQ(200, req->response_headers()->response_code());
1586
1587 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1588 EXPECT_EQ(1, d.response_started_count());
1589 EXPECT_EQ(0, d.received_redirect_count());
1590}
1591
1592TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1593 // Intercept the main request to generate a server error response.
1594 interceptor()->set_intercept_main_request(true);
1595 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1596 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1597
1598 // Intercept that error and respond with an OK response.
1599 interceptor()->set_intercept_final_response(true);
1600 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1601 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1602
1603 TestDelegate d;
1604 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361605 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501606 req->set_method("GET");
1607 req->Start();
1608 base::RunLoop().Run();
1609
1610 // Check that the interceptor got called as expected.
1611 EXPECT_TRUE(interceptor()->did_intercept_main());
1612 EXPECT_TRUE(interceptor()->did_intercept_final());
1613
1614 // Check that we got one good response.
1615 EXPECT_TRUE(req->status().is_success());
1616 EXPECT_EQ(200, req->response_headers()->response_code());
1617 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1618 EXPECT_EQ(1, d.response_started_count());
1619 EXPECT_EQ(0, d.received_redirect_count());
1620}
1621
1622TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1623 // Intercept the main request to simulate a network error.
1624 interceptor()->set_simulate_main_network_error(true);
1625
1626 // Intercept that error and respond with an OK response.
1627 interceptor()->set_intercept_final_response(true);
1628 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1629 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1630
1631 TestDelegate d;
1632 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361633 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501634 req->set_method("GET");
1635 req->Start();
1636 base::RunLoop().Run();
1637
1638 // Check that the interceptor got called as expected.
1639 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1640 EXPECT_TRUE(interceptor()->did_intercept_final());
1641
1642 // Check that we received one good response.
1643 EXPECT_TRUE(req->status().is_success());
1644 EXPECT_EQ(200, req->response_headers()->response_code());
1645 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1646 EXPECT_EQ(1, d.response_started_count());
1647 EXPECT_EQ(0, d.received_redirect_count());
1648}
1649
1650TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1651 // Restart the main request.
1652 interceptor()->set_restart_main_request(true);
1653
1654 // then intercept the new main request and respond with an OK response
1655 interceptor()->set_intercept_main_request(true);
1656 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1657 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1658
1659 TestDelegate d;
1660 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361661 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501662 req->set_method("GET");
1663 req->Start();
1664 base::RunLoop().Run();
1665
1666 // Check that the interceptor got called as expected.
1667 EXPECT_TRUE(interceptor()->did_restart_main());
1668 EXPECT_TRUE(interceptor()->did_intercept_main());
1669
1670 // Check that we received one good response.
1671 EXPECT_TRUE(req->status().is_success());
1672 if (req->status().is_success())
1673 EXPECT_EQ(200, req->response_headers()->response_code());
1674
1675 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1676 EXPECT_EQ(1, d.response_started_count());
1677 EXPECT_EQ(0, d.received_redirect_count());
1678}
1679
1680TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1681 // Intercept the main request and cancel from within the restarted job.
1682 interceptor()->set_cancel_main_request(true);
1683
1684 // Set up to intercept the final response and override it with an OK response.
1685 interceptor()->set_intercept_final_response(true);
1686 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1687 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1688
1689 TestDelegate d;
1690 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361691 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501692 req->set_method("GET");
1693 req->Start();
1694 base::RunLoop().Run();
1695
1696 // Check that the interceptor got called as expected.
1697 EXPECT_TRUE(interceptor()->did_cancel_main());
1698 EXPECT_FALSE(interceptor()->did_intercept_final());
1699
1700 // Check that we see a canceled request.
1701 EXPECT_FALSE(req->status().is_success());
1702 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1703}
1704
1705TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1706 // Intercept the main request and respond with a redirect.
1707 interceptor()->set_intercept_main_request(true);
1708 interceptor()->set_main_headers(
1709 MockURLRequestInterceptor::redirect_headers());
1710 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1711
1712 // Intercept the redirect and cancel from within that job.
1713 interceptor()->set_cancel_redirect_request(true);
1714
1715 // Set up to intercept the final response and override it with an OK response.
1716 interceptor()->set_intercept_final_response(true);
1717 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1718 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1719
1720 TestDelegate d;
1721 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361722 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501723 req->set_method("GET");
1724 req->Start();
1725 base::RunLoop().Run();
1726
1727 // Check that the interceptor got called as expected.
1728 EXPECT_TRUE(interceptor()->did_intercept_main());
1729 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1730 EXPECT_FALSE(interceptor()->did_intercept_final());
1731
1732 // Check that we see a canceled request.
1733 EXPECT_FALSE(req->status().is_success());
1734 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1735}
1736
1737TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1738 // Intercept the main request to simulate a network error.
1739 interceptor()->set_simulate_main_network_error(true);
1740
1741 // Set up to intercept final the response and cancel from within that job.
1742 interceptor()->set_cancel_final_request(true);
1743
1744 TestDelegate d;
1745 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361746 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501747 req->set_method("GET");
1748 req->Start();
1749 base::RunLoop().Run();
1750
1751 // Check that the interceptor got called as expected.
1752 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1753 EXPECT_TRUE(interceptor()->did_cancel_final());
1754
1755 // Check that we see a canceled request.
1756 EXPECT_FALSE(req->status().is_success());
1757 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1758}
1759
1760TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1761 // Intercept the main request and cancel then restart from within that job.
1762 interceptor()->set_cancel_then_restart_main_request(true);
1763
1764 // Set up to intercept the final response and override it with an OK response.
1765 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501766 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1767 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501768
1769 TestDelegate d;
1770 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361771 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501772 req->set_method("GET");
1773 req->Start();
1774 base::RunLoop().Run();
1775
1776 // Check that the interceptor got called as expected.
1777 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1778 EXPECT_FALSE(interceptor()->did_intercept_final());
1779
1780 // Check that we see a canceled request.
1781 EXPECT_FALSE(req->status().is_success());
1782 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591783}
1784
1785// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1786// reused. |connect_time_flags| is used to indicate if there should be dns
1787// or SSL times, and |used_proxy| is used for proxy times.
1788LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1789 int connect_time_flags,
1790 bool used_proxy) {
1791 LoadTimingInfo load_timing;
1792 load_timing.socket_log_id = 1;
1793
1794 if (used_proxy) {
1795 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1796 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1797 }
1798
1799 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1800 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1801 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1802 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1803 }
1804 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1805 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1806 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1807 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1808 }
1809 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1810
1811 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1812 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1813 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1814 return load_timing;
1815}
1816
1817// Same as above, but in the case of a reused socket.
1818LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1819 bool used_proxy) {
1820 LoadTimingInfo load_timing;
1821 load_timing.socket_log_id = 1;
1822 load_timing.socket_reused = true;
1823
1824 if (used_proxy) {
1825 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1826 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1827 }
1828
1829 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1830 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1831 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1832 return load_timing;
1833}
1834
bengr1bf8e942014-11-07 01:36:501835LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1836 const LoadTimingInfo& job_load_timing,
1837 const URLRequestContext& context,
1838 MockURLRequestInterceptor* interceptor) {
1839 interceptor->set_intercept_main_request(true);
1840 interceptor->set_main_request_load_timing_info(job_load_timing);
1841 TestDelegate d;
1842 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361843 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501844 req->Start();
1845 base::RunLoop().Run();
1846
1847 LoadTimingInfo resulting_load_timing;
1848 req->GetLoadTimingInfo(&resulting_load_timing);
1849
1850 // None of these should be modified by the URLRequest.
1851 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1852 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1853 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1854 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1855 EXPECT_EQ(job_load_timing.receive_headers_end,
1856 resulting_load_timing.receive_headers_end);
1857
1858 return resulting_load_timing;
1859}
1860
[email protected]2bba3252013-04-08 19:50:591861// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501862TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591863 base::TimeTicks now = base::TimeTicks::Now();
1864 LoadTimingInfo job_load_timing =
1865 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1866
[email protected]2ca01e52013-10-31 22:05:191867 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501868 RunURLRequestInterceptorLoadTimingTest(
1869 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591870
1871 // Nothing should have been changed by the URLRequest.
1872 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1873 load_timing_result.proxy_resolve_start);
1874 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1875 load_timing_result.proxy_resolve_end);
1876 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1877 load_timing_result.connect_timing.dns_start);
1878 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1879 load_timing_result.connect_timing.dns_end);
1880 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1881 load_timing_result.connect_timing.connect_start);
1882 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1883 load_timing_result.connect_timing.connect_end);
1884 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1885 load_timing_result.connect_timing.ssl_start);
1886 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1887 load_timing_result.connect_timing.ssl_end);
1888
1889 // Redundant sanity check.
1890 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1891}
1892
1893// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501894TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591895 base::TimeTicks now = base::TimeTicks::Now();
1896 LoadTimingInfo job_load_timing =
1897 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1898
[email protected]2ca01e52013-10-31 22:05:191899 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501900 RunURLRequestInterceptorLoadTimingTest(
1901 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591902
1903 // Nothing should have been changed by the URLRequest.
1904 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1905 load_timing_result.proxy_resolve_start);
1906 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1907 load_timing_result.proxy_resolve_end);
1908 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1909 load_timing_result.connect_timing.dns_start);
1910 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1911 load_timing_result.connect_timing.dns_end);
1912 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1913 load_timing_result.connect_timing.connect_start);
1914 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1915 load_timing_result.connect_timing.connect_end);
1916 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1917 load_timing_result.connect_timing.ssl_start);
1918 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1919 load_timing_result.connect_timing.ssl_end);
1920
1921 // Redundant sanity check.
1922 TestLoadTimingNotReusedWithProxy(load_timing_result,
1923 CONNECT_TIMING_HAS_SSL_TIMES);
1924}
1925
1926// Make sure that URLRequest correctly adjusts proxy times when they're before
1927// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101928// the case of reusing a SPDY session. The connected socket is not considered
1929// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591930//
1931// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501932TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591933 base::TimeTicks now = base::TimeTicks::Now();
1934 LoadTimingInfo job_load_timing =
1935 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1936 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1937 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1938 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1939 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1940 job_load_timing.connect_timing.connect_start =
1941 now - base::TimeDelta::FromDays(2);
1942 job_load_timing.connect_timing.connect_end =
1943 now - base::TimeDelta::FromDays(1);
1944
[email protected]2ca01e52013-10-31 22:05:191945 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501946 RunURLRequestInterceptorLoadTimingTest(
1947 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591948
1949 // Proxy times, connect times, and DNS times should all be replaced with
1950 // request_start.
1951 EXPECT_EQ(load_timing_result.request_start,
1952 load_timing_result.proxy_resolve_start);
1953 EXPECT_EQ(load_timing_result.request_start,
1954 load_timing_result.proxy_resolve_end);
1955 EXPECT_EQ(load_timing_result.request_start,
1956 load_timing_result.connect_timing.dns_start);
1957 EXPECT_EQ(load_timing_result.request_start,
1958 load_timing_result.connect_timing.dns_end);
1959 EXPECT_EQ(load_timing_result.request_start,
1960 load_timing_result.connect_timing.connect_start);
1961 EXPECT_EQ(load_timing_result.request_start,
1962 load_timing_result.connect_timing.connect_end);
1963
1964 // Other times should have been left null.
1965 TestLoadTimingNotReusedWithProxy(load_timing_result,
1966 CONNECT_TIMING_HAS_DNS_TIMES);
1967}
1968
1969// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:501970TEST_F(URLRequestInterceptorTest,
1971 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:591972 base::TimeTicks now = base::TimeTicks::Now();
1973 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1974 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1975 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1976
[email protected]2ca01e52013-10-31 22:05:191977 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501978 RunURLRequestInterceptorLoadTimingTest(
1979 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591980
1981 // Proxy times and connect times should all be replaced with request_start.
1982 EXPECT_EQ(load_timing_result.request_start,
1983 load_timing_result.proxy_resolve_start);
1984 EXPECT_EQ(load_timing_result.request_start,
1985 load_timing_result.proxy_resolve_end);
1986
1987 // Other times should have been left null.
1988 TestLoadTimingReusedWithProxy(load_timing_result);
1989}
1990
1991// Make sure that URLRequest correctly adjusts connect times when they're before
1992// |request_start|, due to reusing a connected socket. The connected socket is
1993// not considered reused in this test (May be a preconnect).
1994//
1995// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501996TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:591997 base::TimeTicks now = base::TimeTicks::Now();
1998 LoadTimingInfo job_load_timing =
1999 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2000 job_load_timing.connect_timing.connect_start =
2001 now - base::TimeDelta::FromDays(1);
2002 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2003 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2004 job_load_timing.connect_timing.connect_end =
2005 now - base::TimeDelta::FromDays(4);
2006
[email protected]2ca01e52013-10-31 22:05:192007 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502008 RunURLRequestInterceptorLoadTimingTest(
2009 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592010
2011 // Connect times, and SSL times should be replaced with request_start.
2012 EXPECT_EQ(load_timing_result.request_start,
2013 load_timing_result.connect_timing.connect_start);
2014 EXPECT_EQ(load_timing_result.request_start,
2015 load_timing_result.connect_timing.ssl_start);
2016 EXPECT_EQ(load_timing_result.request_start,
2017 load_timing_result.connect_timing.ssl_end);
2018 EXPECT_EQ(load_timing_result.request_start,
2019 load_timing_result.connect_timing.connect_end);
2020
2021 // Other times should have been left null.
2022 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2023}
2024
2025// Make sure that URLRequest correctly adjusts connect times when they're before
2026// |request_start|, due to reusing a connected socket in the case that there
2027// are also proxy times. The connected socket is not considered reused in this
2028// test (May be a preconnect).
2029//
2030// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502031TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592032 base::TimeTicks now = base::TimeTicks::Now();
2033 LoadTimingInfo job_load_timing =
2034 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2035 job_load_timing.connect_timing.connect_start =
2036 now - base::TimeDelta::FromDays(1);
2037 job_load_timing.connect_timing.connect_end =
2038 now - base::TimeDelta::FromDays(2);
2039
[email protected]2ca01e52013-10-31 22:05:192040 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502041 RunURLRequestInterceptorLoadTimingTest(
2042 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592043
2044 // Connect times should be replaced with proxy_resolve_end.
2045 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2046 load_timing_result.connect_timing.connect_start);
2047 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2048 load_timing_result.connect_timing.connect_end);
2049
2050 // Other times should have been left null.
2051 TestLoadTimingNotReusedWithProxy(load_timing_result,
2052 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2053}
2054
[email protected]316c1e5e2012-09-12 15:17:442055// Check that two different URL requests have different identifiers.
2056TEST_F(URLRequestTest, Identifiers) {
2057 TestDelegate d;
2058 TestURLRequestContext context;
davidben151423e2015-03-23 18:48:362059 scoped_ptr<URLRequest> req(
2060 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2061 scoped_ptr<URLRequest> other_req(
2062 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442063
mmenke19378d22014-09-09 04:12:592064 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442065}
2066
2067// Check that a failure to connect to the proxy is reported to the network
2068// delegate.
2069TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2070 MockHostResolver host_resolver;
2071 host_resolver.rules()->AddSimulatedFailure("*");
2072
[email protected]ceefd7fd2012-11-29 00:36:242073 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442074 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2075
2076 TestDelegate d;
davidben151423e2015-03-23 18:48:362077 scoped_ptr<URLRequest> req(
2078 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192079 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442080
[email protected]f7022f32014-08-21 16:32:192081 req->Start();
[email protected]255620da2013-08-19 13:14:292082 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442083
2084 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192085 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152086 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192087 EXPECT_TRUE(req->proxy_server().IsEmpty());
2088 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2089 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442090
2091 EXPECT_EQ(1, network_delegate.error_count());
2092 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2093 EXPECT_EQ(1, network_delegate.completed_requests());
2094}
2095
[email protected]cba24642014-08-15 20:49:592096// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442097// content is empty.
2098TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2099 TestDelegate d;
davidben151423e2015-03-23 18:48:362100 scoped_ptr<URLRequest> req(
2101 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192102 req->Start();
[email protected]255620da2013-08-19 13:14:292103 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442104 EXPECT_EQ("", d.data_received());
2105 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2106}
2107
[email protected]5033ab82013-03-22 20:17:462108// Make sure that SetPriority actually sets the URLRequest's priority
2109// correctly, both before and after start.
2110TEST_F(URLRequestTest, SetPriorityBasic) {
2111 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192112 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362113 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192114 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462115
[email protected]f7022f32014-08-21 16:32:192116 req->SetPriority(LOW);
2117 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462118
[email protected]f7022f32014-08-21 16:32:192119 req->Start();
2120 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462121
[email protected]f7022f32014-08-21 16:32:192122 req->SetPriority(MEDIUM);
2123 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462124}
2125
2126// Make sure that URLRequest calls SetPriority on a job before calling
2127// Start on it.
2128TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2129 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192130 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362131 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192132 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462133
2134 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192135 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502136 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462137 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2138
[email protected]f7022f32014-08-21 16:32:192139 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462140
[email protected]f7022f32014-08-21 16:32:192141 req->Start();
[email protected]5033ab82013-03-22 20:17:462142 EXPECT_EQ(LOW, job->priority());
2143}
2144
2145// Make sure that URLRequest passes on its priority updates to its
2146// job.
2147TEST_F(URLRequestTest, SetJobPriority) {
2148 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192149 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362150 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462151
2152 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192153 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502154 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462155
[email protected]f7022f32014-08-21 16:32:192156 req->SetPriority(LOW);
2157 req->Start();
[email protected]5033ab82013-03-22 20:17:462158 EXPECT_EQ(LOW, job->priority());
2159
[email protected]f7022f32014-08-21 16:32:192160 req->SetPriority(MEDIUM);
2161 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462162 EXPECT_EQ(MEDIUM, job->priority());
2163}
2164
[email protected]bb1c4662013-11-14 00:00:072165// Setting the IGNORE_LIMITS load flag should be okay if the priority
2166// is MAXIMUM_PRIORITY.
2167TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2168 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192169 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362170 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192171 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072172
2173 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192174 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]bb1c4662013-11-14 00:00:072175 AddTestInterceptor()->set_main_intercept_job(job.get());
2176
[email protected]f7022f32014-08-21 16:32:192177 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2178 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072179
[email protected]f7022f32014-08-21 16:32:192180 req->SetPriority(MAXIMUM_PRIORITY);
2181 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072182
[email protected]f7022f32014-08-21 16:32:192183 req->Start();
2184 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072185 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2186}
2187
[email protected]ce7d0cbc2013-05-03 18:57:222188// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:442189#if !defined(OS_IOS)
nick5d570de92015-05-04 20:16:162190namespace {
2191
2192// Less verbose way of running a simple testserver for the tests below.
[email protected]ce7d0cbc2013-05-03 18:57:222193class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442194 public:
[email protected]6cdfd7f2013-02-08 20:40:152195 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:222196 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162197 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222198 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:442199 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:222200 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162201 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222202 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:442203};
2204
nick5d570de92015-05-04 20:16:162205} // namespace
2206
[email protected]f2f31b32013-01-16 23:24:092207TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442208 LocalHttpTestServer test_server;
2209 ASSERT_TRUE(test_server.Start());
2210
2211 TestURLRequestContext context;
2212 scoped_refptr<DelayedCookieMonster> delayed_cm =
2213 new DelayedCookieMonster();
2214 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502215 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442216
2217 // Set up a cookie.
2218 {
2219 TestNetworkDelegate network_delegate;
2220 context.set_network_delegate(&network_delegate);
2221 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192222 scoped_ptr<URLRequest> req(context.CreateRequest(
2223 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362224 &d));
[email protected]f7022f32014-08-21 16:32:192225 req->Start();
[email protected]255620da2013-08-19 13:14:292226 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442227 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2228 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2229 EXPECT_EQ(1, network_delegate.set_cookie_count());
2230 }
2231
2232 // Verify that the cookie is set.
2233 {
2234 TestNetworkDelegate network_delegate;
2235 context.set_network_delegate(&network_delegate);
2236 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192237 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:362238 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192239 req->Start();
[email protected]255620da2013-08-19 13:14:292240 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442241
2242 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2243 != std::string::npos);
2244 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2245 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2246 }
2247}
2248
[email protected]f2f31b32013-01-16 23:24:092249TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442250 LocalHttpTestServer test_server;
2251 ASSERT_TRUE(test_server.Start());
2252
2253 // Set up a cookie.
2254 {
2255 TestNetworkDelegate network_delegate;
2256 default_context_.set_network_delegate(&network_delegate);
2257 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192258 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2259 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362260 &d));
[email protected]f7022f32014-08-21 16:32:192261 req->Start();
[email protected]255620da2013-08-19 13:14:292262 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442263 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2264 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2265 }
2266
2267 // Verify that the cookie is set.
2268 {
2269 TestNetworkDelegate network_delegate;
2270 default_context_.set_network_delegate(&network_delegate);
2271 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192272 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362273 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192274 req->Start();
[email protected]255620da2013-08-19 13:14:292275 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442276
2277 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2278 != std::string::npos);
2279 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2280 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2281 }
2282
2283 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2284 {
2285 TestNetworkDelegate network_delegate;
2286 default_context_.set_network_delegate(&network_delegate);
2287 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192288 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362289 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192290 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2291 req->Start();
[email protected]255620da2013-08-19 13:14:292292 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442293
2294 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2295 == std::string::npos);
2296
2297 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2298 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2299 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2300 }
2301}
2302
2303TEST_F(URLRequestTest, DoNotSaveCookies) {
2304 LocalHttpTestServer test_server;
2305 ASSERT_TRUE(test_server.Start());
2306
2307 // Set up a cookie.
2308 {
2309 TestNetworkDelegate network_delegate;
2310 default_context_.set_network_delegate(&network_delegate);
2311 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192312 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2313 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362314 &d));
[email protected]f7022f32014-08-21 16:32:192315 req->Start();
[email protected]255620da2013-08-19 13:14:292316 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442317
2318 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2319 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2320 EXPECT_EQ(1, network_delegate.set_cookie_count());
2321 }
2322
2323 // Try to set-up another cookie and update the previous cookie.
2324 {
2325 TestNetworkDelegate network_delegate;
2326 default_context_.set_network_delegate(&network_delegate);
2327 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192328 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442329 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362330 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192331 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2332 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442333
[email protected]255620da2013-08-19 13:14:292334 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442335
2336 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2337 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2338 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2339 EXPECT_EQ(0, network_delegate.set_cookie_count());
2340 }
2341
2342 // Verify the cookies weren't saved or updated.
2343 {
2344 TestNetworkDelegate network_delegate;
2345 default_context_.set_network_delegate(&network_delegate);
2346 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192347 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362348 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192349 req->Start();
[email protected]255620da2013-08-19 13:14:292350 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442351
2352 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2353 == std::string::npos);
2354 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2355 != std::string::npos);
2356
2357 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2358 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2359 EXPECT_EQ(0, network_delegate.set_cookie_count());
2360 }
2361}
2362
2363TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2364 LocalHttpTestServer test_server;
2365 ASSERT_TRUE(test_server.Start());
2366
2367 // Set up a cookie.
2368 {
2369 TestNetworkDelegate network_delegate;
2370 default_context_.set_network_delegate(&network_delegate);
2371 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192372 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2373 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362374 &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_EQ(0, network_delegate.blocked_get_cookies_count());
2379 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2380 }
2381
2382 // Verify that the cookie is set.
2383 {
2384 TestNetworkDelegate network_delegate;
2385 default_context_.set_network_delegate(&network_delegate);
2386 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192387 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362388 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192389 req->Start();
[email protected]255620da2013-08-19 13:14:292390 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442391
2392 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2393 != std::string::npos);
2394
2395 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2396 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2397 }
2398
2399 // Verify that the cookie isn't sent.
2400 {
2401 TestNetworkDelegate network_delegate;
2402 default_context_.set_network_delegate(&network_delegate);
2403 TestDelegate d;
2404 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192405 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362406 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192407 req->Start();
[email protected]255620da2013-08-19 13:14:292408 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442409
2410 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2411 == std::string::npos);
2412
[email protected]22e045f2013-09-20 03:54:032413 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442414 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2415 }
2416}
2417
2418TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2419 LocalHttpTestServer test_server;
2420 ASSERT_TRUE(test_server.Start());
2421
2422 // Set up a cookie.
2423 {
2424 TestNetworkDelegate network_delegate;
2425 default_context_.set_network_delegate(&network_delegate);
2426 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192427 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2428 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362429 &d));
[email protected]f7022f32014-08-21 16:32:192430 req->Start();
[email protected]255620da2013-08-19 13:14:292431 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442432
2433 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2434 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2435 }
2436
2437 // Try to set-up another cookie and update the previous cookie.
2438 {
2439 TestNetworkDelegate network_delegate;
2440 default_context_.set_network_delegate(&network_delegate);
2441 TestDelegate d;
2442 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192443 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442444 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362445 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192446 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442447
[email protected]255620da2013-08-19 13:14:292448 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442449
2450 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2451 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2452 }
2453
2454 // Verify the cookies weren't saved or updated.
2455 {
2456 TestNetworkDelegate network_delegate;
2457 default_context_.set_network_delegate(&network_delegate);
2458 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192459 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362460 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192461 req->Start();
[email protected]255620da2013-08-19 13:14:292462 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442463
2464 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2465 == std::string::npos);
2466 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2467 != std::string::npos);
2468
2469 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2470 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2471 }
2472}
2473
2474TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2475 LocalHttpTestServer test_server;
2476 ASSERT_TRUE(test_server.Start());
2477
2478 // Set up an empty cookie.
2479 {
2480 TestNetworkDelegate network_delegate;
2481 default_context_.set_network_delegate(&network_delegate);
2482 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192483 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362484 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192485 req->Start();
[email protected]255620da2013-08-19 13:14:292486 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442487
2488 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2489 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2490 EXPECT_EQ(0, network_delegate.set_cookie_count());
2491 }
2492}
2493
2494TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2495 LocalHttpTestServer test_server;
2496 ASSERT_TRUE(test_server.Start());
2497
2498 // Set up a cookie.
2499 {
2500 TestNetworkDelegate network_delegate;
2501 default_context_.set_network_delegate(&network_delegate);
2502 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192503 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2504 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362505 &d));
[email protected]f7022f32014-08-21 16:32:192506 req->Start();
[email protected]255620da2013-08-19 13:14:292507 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442508
2509 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2510 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2511 }
2512
2513 // Verify that the cookie is set.
2514 {
2515 TestNetworkDelegate network_delegate;
2516 default_context_.set_network_delegate(&network_delegate);
2517 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192518 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362519 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192520 req->Start();
[email protected]255620da2013-08-19 13:14:292521 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442522
2523 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2524 != std::string::npos);
2525
2526 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2527 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2528 }
2529
2530 // Verify that the cookie isn't sent.
2531 {
2532 TestNetworkDelegate network_delegate;
2533 default_context_.set_network_delegate(&network_delegate);
2534 TestDelegate d;
2535 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192536 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362537 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192538 req->Start();
[email protected]255620da2013-08-19 13:14:292539 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442540
2541 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2542 == std::string::npos);
2543
[email protected]22e045f2013-09-20 03:54:032544 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442545 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2546 }
2547}
2548
2549TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2550 LocalHttpTestServer test_server;
2551 ASSERT_TRUE(test_server.Start());
2552
2553 // Set up a cookie.
2554 {
2555 TestNetworkDelegate network_delegate;
2556 default_context_.set_network_delegate(&network_delegate);
2557 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192558 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2559 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362560 &d));
[email protected]f7022f32014-08-21 16:32:192561 req->Start();
[email protected]255620da2013-08-19 13:14:292562 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442563
2564 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2565 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2566 }
2567
2568 // Try to set-up another cookie and update the previous cookie.
2569 {
2570 TestNetworkDelegate network_delegate;
2571 default_context_.set_network_delegate(&network_delegate);
2572 TestDelegate d;
2573 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192574 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442575 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362576 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192577 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442578
[email protected]255620da2013-08-19 13:14:292579 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442580
2581 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2582 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2583 }
2584
2585 // Verify the cookies weren't saved or updated.
2586 {
2587 TestNetworkDelegate network_delegate;
2588 default_context_.set_network_delegate(&network_delegate);
2589 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192590 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362591 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192592 req->Start();
[email protected]255620da2013-08-19 13:14:292593 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442594
2595 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2596 == std::string::npos);
2597 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2598 != std::string::npos);
2599
2600 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2601 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2602 }
2603}
2604
mkwst3f3daac2015-02-26 20:15:262605TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2606 LocalHttpTestServer test_server;
2607 ASSERT_TRUE(test_server.Start());
2608
2609 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2610 // LocalHttpTestServer points).
2611 {
2612 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412613 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262614 default_context_.set_network_delegate(&network_delegate);
2615
2616 TestDelegate d;
2617 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2618 test_server.GetURL(
2619 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
davidben151423e2015-03-23 18:48:362620 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262621 req->Start();
2622 base::RunLoop().Run();
2623 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2624 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2625 EXPECT_EQ(1, network_delegate.set_cookie_count());
2626 }
2627
2628 // Verify that the cookie is sent for first-party requests.
2629 {
2630 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412631 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262632 default_context_.set_network_delegate(&network_delegate);
2633 TestDelegate d;
2634 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362635 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472636 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst3f3daac2015-02-26 20:15:262637 req->Start();
2638 base::RunLoop().Run();
2639
2640 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2641 std::string::npos);
2642 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2643 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2644 }
2645
2646 // Verify that the cookie is not-sent for non-first-party requests.
2647 {
2648 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412649 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262650 default_context_.set_network_delegate(&network_delegate);
2651 TestDelegate d;
2652 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362653 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262654 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2655 req->Start();
2656 base::RunLoop().Run();
2657
2658 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2659 std::string::npos);
2660 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2661 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2662 }
2663}
2664
mkwst0513c9d2015-04-01 05:53:152665TEST_F(URLRequestTest, FirstPartyOnlyCookiesDisabled) {
2666 LocalHttpTestServer test_server;
2667 ASSERT_TRUE(test_server.Start());
2668
2669 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2670 // LocalHttpTestServer points).
2671 {
2672 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412673 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152674 default_context_.set_network_delegate(&network_delegate);
2675
2676 TestDelegate d;
2677 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2678 test_server.GetURL(
2679 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
2680 DEFAULT_PRIORITY, &d));
2681 req->Start();
2682 base::RunLoop().Run();
2683 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2684 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2685 EXPECT_EQ(1, network_delegate.set_cookie_count());
2686 }
2687
2688 // Verify that the cookie is sent for first-party requests.
2689 {
2690 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412691 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152692 default_context_.set_network_delegate(&network_delegate);
2693 TestDelegate d;
2694 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2695 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472696 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst0513c9d2015-04-01 05:53:152697 req->Start();
2698 base::RunLoop().Run();
2699
2700 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2701 std::string::npos);
2702 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2703 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2704 }
2705
2706 // Verify that the cookie is also sent for non-first-party requests.
2707 {
2708 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412709 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152710 default_context_.set_network_delegate(&network_delegate);
2711 TestDelegate d;
2712 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2713 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2714 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2715 req->Start();
2716 base::RunLoop().Run();
2717
2718 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2719 std::string::npos);
2720 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2721 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2722 }
2723}
2724
mmenkefb18c772015-09-30 22:22:502725// Tests that a request is cancelled while entering suspend mode. Uses mocks
2726// rather than a spawned test server because the connection used to talk to
2727// the test server is affected by entering suspend mode on Android.
2728TEST_F(URLRequestTest, CancelOnSuspend) {
2729 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
2730 base::PowerMonitor power_monitor(make_scoped_ptr(power_monitor_source));
2731
2732 URLRequestFailedJob::AddUrlHandler();
2733
2734 TestDelegate d;
2735 // Request that just hangs.
2736 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
2737 scoped_ptr<URLRequest> r(
2738 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
2739 r->Start();
2740
2741 power_monitor_source->Suspend();
2742 // Wait for the suspend notification to cause the request to fail.
2743 base::RunLoop().Run();
2744 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
2745 EXPECT_TRUE(d.request_failed());
2746 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2747
2748 URLRequestFilter::GetInstance()->ClearHandlers();
2749
2750 // Shouldn't be needed, but just in case.
2751 power_monitor_source->Resume();
2752}
2753
[email protected]5095cd72012-11-01 10:29:162754// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2755// value for the |fixed_date| argument given to the constructor.
2756class FixedDateNetworkDelegate : public TestNetworkDelegate {
2757 public:
2758 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2759 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:202760 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:162761
[email protected]cba24642014-08-15 20:49:592762 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:202763 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592764 URLRequest* request,
2765 const CompletionCallback& callback,
2766 const HttpResponseHeaders* original_response_headers,
2767 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:132768 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:162769
2770 private:
2771 std::string fixed_date_;
2772
2773 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2774};
2775
2776int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592777 URLRequest* request,
2778 const CompletionCallback& callback,
2779 const HttpResponseHeaders* original_response_headers,
2780 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:162781 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:592782 HttpResponseHeaders* new_response_headers =
2783 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:162784
2785 new_response_headers->RemoveHeader("Date");
2786 new_response_headers->AddHeader("Date: " + fixed_date_);
2787
2788 *override_response_headers = new_response_headers;
2789 return TestNetworkDelegate::OnHeadersReceived(request,
2790 callback,
2791 original_response_headers,
[email protected]5f714132014-03-26 10:41:162792 override_response_headers,
2793 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:162794}
2795
2796// Test that cookie expiration times are adjusted for server/client clock
2797// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2798// headers by defaulting to GMT. (crbug.com/135131)
2799TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2800 LocalHttpTestServer test_server;
2801 ASSERT_TRUE(test_server.Start());
2802
2803 // Set up an expired cookie.
2804 {
2805 TestNetworkDelegate network_delegate;
2806 default_context_.set_network_delegate(&network_delegate);
2807 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192808 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192809 test_server.GetURL(
2810 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362811 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192812 req->Start();
[email protected]255620da2013-08-19 13:14:292813 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162814 }
2815 // Verify that the cookie is not set.
2816 {
2817 TestNetworkDelegate network_delegate;
2818 default_context_.set_network_delegate(&network_delegate);
2819 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192820 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362821 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192822 req->Start();
[email protected]255620da2013-08-19 13:14:292823 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162824
2825 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2826 }
2827 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2828 {
2829 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2830 default_context_.set_network_delegate(&network_delegate);
2831 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192832 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192833 test_server.GetURL(
2834 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362835 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192836 req->Start();
[email protected]255620da2013-08-19 13:14:292837 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162838 }
2839 // Verify that the cookie is set.
2840 {
2841 TestNetworkDelegate network_delegate;
2842 default_context_.set_network_delegate(&network_delegate);
2843 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192844 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362845 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192846 req->Start();
[email protected]255620da2013-08-19 13:14:292847 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162848
2849 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2850 }
2851}
2852
2853
[email protected]316c1e5e2012-09-12 15:17:442854// Check that it is impossible to change the referrer in the extra headers of
2855// an URLRequest.
2856TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2857 LocalHttpTestServer test_server;
2858 ASSERT_TRUE(test_server.Start());
2859
2860 // If extra headers contain referer and the request contains a referer,
2861 // only the latter shall be respected.
2862 {
2863 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192864 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362865 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192866 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442867
2868 HttpRequestHeaders headers;
2869 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192870 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:442871
[email protected]f7022f32014-08-21 16:32:192872 req->Start();
[email protected]255620da2013-08-19 13:14:292873 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442874
2875 EXPECT_EQ("http://foo.com/", d.data_received());
2876 }
2877
2878 // If extra headers contain a referer but the request does not, no referer
2879 // shall be sent in the header.
2880 {
2881 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192882 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362883 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442884
2885 HttpRequestHeaders headers;
2886 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192887 req->SetExtraRequestHeaders(headers);
2888 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:442889
[email protected]f7022f32014-08-21 16:32:192890 req->Start();
[email protected]255620da2013-08-19 13:14:292891 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442892
2893 EXPECT_EQ("None", d.data_received());
2894 }
2895}
2896
[email protected]b89290212009-08-14 22:37:352897class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112898 public:
mmenke9f2ec60c2015-06-01 20:59:472899 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:112900
[email protected]b89290212009-08-14 22:37:352901 protected:
[email protected]21184962011-10-26 00:50:302902 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2903 // |request_method| is the method to use for the initial request.
2904 // |redirect_method| is the method that is expected to be used for the second
2905 // request, after redirection.
2906 // If |include_data| is true, data is uploaded with the request. The
2907 // response body is expected to match it exactly, if and only if
2908 // |request_method| == |redirect_method|.
2909 void HTTPRedirectMethodTest(const GURL& redirect_url,
2910 const std::string& request_method,
2911 const std::string& redirect_method,
2912 bool include_data) {
2913 static const char kData[] = "hello world";
2914 TestDelegate d;
davidben151423e2015-03-23 18:48:362915 scoped_ptr<URLRequest> req(
2916 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192917 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:302918 if (include_data) {
mmenkecbc2b712014-10-09 20:29:072919 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:302920 HttpRequestHeaders headers;
2921 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:512922 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:542923 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:192924 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:302925 }
[email protected]f7022f32014-08-21 16:32:192926 req->Start();
[email protected]255620da2013-08-19 13:14:292927 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:192928 EXPECT_EQ(redirect_method, req->method());
2929 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
2930 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:302931 if (include_data) {
2932 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:542933 EXPECT_TRUE(req->extra_request_headers().HasHeader(
2934 HttpRequestHeaders::kContentLength));
2935 EXPECT_TRUE(req->extra_request_headers().HasHeader(
2936 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:302937 EXPECT_EQ(kData, d.data_received());
2938 } else {
svaldez5b3a8972015-10-09 23:23:542939 EXPECT_FALSE(req->extra_request_headers().HasHeader(
2940 HttpRequestHeaders::kContentLength));
2941 EXPECT_FALSE(req->extra_request_headers().HasHeader(
2942 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:302943 EXPECT_NE(kData, d.data_received());
2944 }
2945 }
2946 if (HasFailure())
2947 LOG(WARNING) << "Request method was: " << request_method;
2948 }
2949
jww5fe460ff2015-03-28 00:22:512950 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2951 // |request_method| is the method to use for the initial request.
2952 // |redirect_method| is the method that is expected to be used for the second
2953 // request, after redirection.
2954 // |origin_value| is the expected value for the Origin header after
2955 // redirection. If empty, expects that there will be no Origin header.
2956 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
2957 const std::string& request_method,
2958 const std::string& redirect_method,
2959 const std::string& origin_value) {
2960 TestDelegate d;
2961 scoped_ptr<URLRequest> req(
2962 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
2963 req->set_method(request_method);
2964 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
2965 redirect_url.GetOrigin().spec(), false);
2966 req->Start();
2967
2968 base::RunLoop().Run();
2969
2970 EXPECT_EQ(redirect_method, req->method());
2971 // Note that there is no check for request success here because, for
2972 // purposes of testing, the request very well may fail. For example, if the
2973 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
2974 // origin, there is not an HTTPS server in this unit test framework, so the
2975 // request would fail. However, that's fine, as long as the request headers
2976 // are in order and pass the checks below.
2977 if (origin_value.empty()) {
2978 EXPECT_FALSE(
2979 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
2980 } else {
2981 std::string origin_header;
2982 EXPECT_TRUE(req->extra_request_headers().GetHeader(
2983 HttpRequestHeaders::kOrigin, &origin_header));
2984 EXPECT_EQ(origin_value, origin_header);
2985 }
2986 }
2987
[email protected]762d2db2010-01-11 19:03:012988 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012989 const int kMsgSize = 20000; // multiple of 10
2990 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482991 char* uploadBytes = new char[kMsgSize+1];
2992 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012993 char marker = 'a';
2994 for (int idx = 0; idx < kMsgSize/10; idx++) {
2995 memcpy(ptr, "----------", 10);
2996 ptr += 10;
2997 if (idx % 100 == 0) {
2998 ptr--;
2999 *ptr++ = marker;
3000 if (++marker > 'z')
3001 marker = 'a';
3002 }
3003 }
3004 uploadBytes[kMsgSize] = '\0';
3005
[email protected]762d2db2010-01-11 19:03:013006 for (int i = 0; i < kIterations; ++i) {
3007 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193008 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363009 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193010 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013011
mmenkecbc2b712014-10-09 20:29:073012 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013013
[email protected]f7022f32014-08-21 16:32:193014 r->Start();
3015 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013016
[email protected]255620da2013-08-19 13:14:293017 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013018
[email protected]329b68b2012-11-14 17:54:273019 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:193020 << "request failed: " << r->status().status()
3021 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:013022
3023 EXPECT_FALSE(d.received_data_before_response());
3024 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013025 }
3026 delete[] uploadBytes;
3027 }
3028
[email protected]ef2bf422012-05-11 03:27:093029 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:223030 r->AppendChunkToUpload("a", 1, false);
3031 r->AppendChunkToUpload("bcd", 3, false);
3032 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
3033 r->AppendChunkToUpload("\r\n\r\n", 4, false);
3034 r->AppendChunkToUpload("0", 1, false);
3035 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:113036 }
3037
[email protected]ef2bf422012-05-11 03:27:093038 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:113039 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:273040 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:113041 "abcdthis is a longer chunk than before.\r\n\r\n02323";
3042
[email protected]329b68b2012-11-14 17:54:273043 ASSERT_EQ(1, d->response_started_count())
3044 << "request failed: " << r->status().status()
3045 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:113046
3047 EXPECT_FALSE(d->received_data_before_response());
3048
[email protected]329b68b2012-11-14 17:54:273049 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
3050 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:113051 }
3052
[email protected]ede03212012-09-07 12:52:263053 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343054 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193055 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3056 test_server_.GetURL("set-many-cookies?" +
davidben151423e2015-03-23 18:48:363057 base::IntToString(num_cookies)),
3058 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343059
[email protected]f7022f32014-08-21 16:32:193060 r->Start();
3061 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343062
[email protected]255620da2013-08-19 13:14:293063 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343064
[email protected]f7022f32014-08-21 16:32:193065 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:343066
[email protected]ede03212012-09-07 12:52:263067 if (!is_success) {
[email protected]f7022f32014-08-21 16:32:193068 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:343069 // The test server appears to be unable to handle subsequent requests
3070 // after this error is triggered. Force it to restart.
3071 EXPECT_TRUE(test_server_.Stop());
3072 EXPECT_TRUE(test_server_.Start());
3073 }
3074
3075 return is_success;
3076 }
3077
bengr1bf8e942014-11-07 01:36:503078 LocalHttpTestServer* test_server() {
3079 return &test_server_;
3080 }
3081
3082 protected:
[email protected]1700c6a2012-02-22 18:07:073083 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353084};
3085
[email protected]95409e12010-08-17 20:07:113086// In this unit test, we're using the HTTPTestServer as a proxy server and
3087// issuing a CONNECT request with the magic host name "www.redirect.com".
3088// The HTTPTestServer will return a 302 response, which we should not
3089// follow.
[email protected]f2f31b32013-01-16 23:24:093090TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:113091 ASSERT_TRUE(test_server_.Start());
3092
[email protected]ceefd7fd2012-11-29 00:36:243093 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043094 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193095 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503096
[email protected]d1ec59082009-02-11 02:48:153097 TestDelegate d;
3098 {
[email protected]f7022f32014-08-21 16:32:193099 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363100 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193101 r->Start();
3102 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153103
[email protected]255620da2013-08-19 13:14:293104 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153105
[email protected]f7022f32014-08-21 16:32:193106 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153107 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193108 EXPECT_TRUE(r->proxy_server().IsEmpty());
3109 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083110 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153111 // We should not have followed the redirect.
3112 EXPECT_EQ(0, d.received_redirect_count());
3113 }
3114}
3115
[email protected]8202d0c2011-02-23 08:31:143116// This is the same as the previous test, but checks that the network delegate
3117// registers the error.
[email protected]c044616e2013-02-20 02:01:263118TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:143119 ASSERT_TRUE(test_server_.Start());
3120
[email protected]ceefd7fd2012-11-29 00:36:243121 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043122 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193123 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503124
[email protected]8202d0c2011-02-23 08:31:143125 TestDelegate d;
3126 {
[email protected]f7022f32014-08-21 16:32:193127 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363128 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193129 r->Start();
3130 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143131
[email protected]255620da2013-08-19 13:14:293132 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143133
[email protected]f7022f32014-08-21 16:32:193134 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153135 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193136 EXPECT_TRUE(r->proxy_server().IsEmpty());
3137 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143138 EXPECT_EQ(1, d.response_started_count());
3139 // We should not have followed the redirect.
3140 EXPECT_EQ(0, d.received_redirect_count());
3141
3142 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053143 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143144 }
3145}
3146
[email protected]dc5a5cf2012-09-26 02:49:303147// Tests that we can block and asynchronously return OK in various stages.
3148TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3149 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3150 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3151 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3152 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3153 };
3154 static const size_t blocking_stages_length = arraysize(blocking_stages);
3155
3156 ASSERT_TRUE(test_server_.Start());
3157
3158 TestDelegate d;
3159 BlockingNetworkDelegate network_delegate(
3160 BlockingNetworkDelegate::USER_CALLBACK);
3161 network_delegate.set_block_on(
3162 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3163 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3164 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3165
3166 TestURLRequestContext context(true);
3167 context.set_network_delegate(&network_delegate);
3168 context.Init();
3169
3170 {
[email protected]f7022f32014-08-21 16:32:193171 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363172 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303173
[email protected]f7022f32014-08-21 16:32:193174 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303175 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293176 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303177 EXPECT_EQ(blocking_stages[i],
3178 network_delegate.stage_blocked_for_callback());
3179 network_delegate.DoCallback(OK);
3180 }
[email protected]255620da2013-08-19 13:14:293181 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193182 EXPECT_EQ(200, r->GetResponseCode());
3183 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303184 EXPECT_EQ(1, network_delegate.created_requests());
3185 EXPECT_EQ(0, network_delegate.destroyed_requests());
3186 }
3187 EXPECT_EQ(1, network_delegate.destroyed_requests());
3188}
3189
[email protected]4c76d7c2011-04-15 19:14:123190// Tests that the network delegate can block and cancel a request.
3191TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
3192 ASSERT_TRUE(test_server_.Start());
3193
3194 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303195 BlockingNetworkDelegate network_delegate(
3196 BlockingNetworkDelegate::AUTO_CALLBACK);
3197 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3198 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123199
[email protected]d5a4dd62012-05-23 01:41:043200 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193201 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503202
[email protected]4c76d7c2011-04-15 19:14:123203 {
[email protected]f7022f32014-08-21 16:32:193204 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363205 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123206
[email protected]f7022f32014-08-21 16:32:193207 r->Start();
[email protected]255620da2013-08-19 13:14:293208 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123209
[email protected]f7022f32014-08-21 16:32:193210 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153211 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193212 EXPECT_TRUE(r->proxy_server().IsEmpty());
3213 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123214 EXPECT_EQ(1, network_delegate.created_requests());
3215 EXPECT_EQ(0, network_delegate.destroyed_requests());
3216 }
3217 EXPECT_EQ(1, network_delegate.destroyed_requests());
3218}
3219
[email protected]b4438d32012-09-27 06:15:303220// Helper function for NetworkDelegateCancelRequestAsynchronously and
3221// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3222// delegate operating in |block_mode| and a request for |url|. It blocks the
3223// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3224void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3225 BlockingNetworkDelegate::Stage stage,
3226 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363227 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303228 BlockingNetworkDelegate network_delegate(block_mode);
3229 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3230 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363231
[email protected]b4438d32012-09-27 06:15:303232 TestURLRequestContext context(true);
3233 context.set_network_delegate(&network_delegate);
3234 context.Init();
[email protected]3cd384c602011-08-31 16:12:363235
3236 {
davidben151423e2015-03-23 18:48:363237 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363238
[email protected]f7022f32014-08-21 16:32:193239 r->Start();
[email protected]255620da2013-08-19 13:14:293240 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363241
[email protected]f7022f32014-08-21 16:32:193242 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153243 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193244 EXPECT_TRUE(r->proxy_server().IsEmpty());
3245 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363246 EXPECT_EQ(1, network_delegate.created_requests());
3247 EXPECT_EQ(0, network_delegate.destroyed_requests());
3248 }
3249 EXPECT_EQ(1, network_delegate.destroyed_requests());
3250}
3251
[email protected]b4438d32012-09-27 06:15:303252// The following 3 tests check that the network delegate can cancel a request
3253// synchronously in various stages of the request.
3254TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
3255 ASSERT_TRUE(test_server_.Start());
3256 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3257 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453258 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303259}
3260
3261TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
3262 ASSERT_TRUE(test_server_.Start());
3263 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3264 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453265 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303266}
3267
3268TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
3269 ASSERT_TRUE(test_server_.Start());
3270 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3271 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453272 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303273}
3274
3275// The following 3 tests check that the network delegate can cancel a request
3276// asynchronously in various stages of the request.
3277TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
3278 ASSERT_TRUE(test_server_.Start());
3279 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3280 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453281 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303282}
3283
3284TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
3285 ASSERT_TRUE(test_server_.Start());
3286 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3287 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453288 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303289}
3290
3291TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
3292 ASSERT_TRUE(test_server_.Start());
3293 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3294 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453295 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303296}
3297
[email protected]4c76d7c2011-04-15 19:14:123298// Tests that the network delegate can block and redirect a request to a new
3299// URL.
3300TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
3301 ASSERT_TRUE(test_server_.Start());
3302
3303 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303304 BlockingNetworkDelegate network_delegate(
3305 BlockingNetworkDelegate::AUTO_CALLBACK);
3306 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:123307 GURL redirect_url(test_server_.GetURL("simple.html"));
3308 network_delegate.set_redirect_url(redirect_url);
3309
[email protected]d5a4dd62012-05-23 01:41:043310 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193311 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503312
[email protected]4c76d7c2011-04-15 19:14:123313 {
[email protected]8f1ac082011-04-19 21:14:133314 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363315 scoped_ptr<URLRequest> r(
3316 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123317
[email protected]6be6fa92014-08-06 23:44:563318 // Quit after hitting the redirect, so can check the headers.
3319 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193320 r->Start();
[email protected]255620da2013-08-19 13:14:293321 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123322
[email protected]6be6fa92014-08-06 23:44:563323 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193324 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3325 EXPECT_EQ(307, r->GetResponseCode());
3326 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563327 std::string location;
[email protected]f7022f32014-08-21 16:32:193328 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3329 &location));
[email protected]6be6fa92014-08-06 23:44:563330 EXPECT_EQ(redirect_url, GURL(location));
3331
3332 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193333 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563334 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193335 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3336 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273337 EXPECT_EQ(
3338 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3339 EXPECT_TRUE(
3340 network_delegate.last_observed_proxy().Equals(
3341 test_server_.host_port_pair()));
3342
[email protected]f7022f32014-08-21 16:32:193343 EXPECT_EQ(0, r->status().error());
3344 EXPECT_EQ(redirect_url, r->url());
3345 EXPECT_EQ(original_url, r->original_url());
3346 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123347 EXPECT_EQ(1, network_delegate.created_requests());
3348 EXPECT_EQ(0, network_delegate.destroyed_requests());
3349 }
3350 EXPECT_EQ(1, network_delegate.destroyed_requests());
3351}
3352
[email protected]b813ed72012-04-05 08:21:363353// Tests that the network delegate can block and redirect a request to a new
3354// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3355TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
3356 ASSERT_TRUE(test_server_.Start());
3357
3358 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303359 BlockingNetworkDelegate network_delegate(
3360 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:363361 GURL redirect_url(test_server_.GetURL("simple.html"));
3362 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363363
[email protected]d5a4dd62012-05-23 01:41:043364 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193365 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363366
3367 {
3368 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363369 scoped_ptr<URLRequest> r(
3370 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363371
[email protected]6be6fa92014-08-06 23:44:563372 // Quit after hitting the redirect, so can check the headers.
3373 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193374 r->Start();
[email protected]255620da2013-08-19 13:14:293375 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363376
[email protected]6be6fa92014-08-06 23:44:563377 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193378 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3379 EXPECT_EQ(307, r->GetResponseCode());
3380 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563381 std::string location;
[email protected]f7022f32014-08-21 16:32:193382 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3383 &location));
[email protected]6be6fa92014-08-06 23:44:563384 EXPECT_EQ(redirect_url, GURL(location));
3385
3386 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193387 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563388 base::RunLoop().Run();
3389
[email protected]f7022f32014-08-21 16:32:193390 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3391 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273392 EXPECT_EQ(
3393 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3394 EXPECT_TRUE(
3395 network_delegate.last_observed_proxy().Equals(
3396 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193397 EXPECT_EQ(0, r->status().error());
3398 EXPECT_EQ(redirect_url, r->url());
3399 EXPECT_EQ(original_url, r->original_url());
3400 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363401 EXPECT_EQ(1, network_delegate.created_requests());
3402 EXPECT_EQ(0, network_delegate.destroyed_requests());
3403 }
3404 EXPECT_EQ(1, network_delegate.destroyed_requests());
3405}
3406
[email protected]3c5ca8c2011-09-29 01:14:513407// Tests that redirects caused by the network delegate preserve POST data.
3408TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3409 ASSERT_TRUE(test_server_.Start());
3410
3411 const char kData[] = "hello world";
3412
3413 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303414 BlockingNetworkDelegate network_delegate(
3415 BlockingNetworkDelegate::AUTO_CALLBACK);
3416 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:513417 GURL redirect_url(test_server_.GetURL("echo"));
3418 network_delegate.set_redirect_url(redirect_url);
3419
[email protected]ef2bf422012-05-11 03:27:093420 TestURLRequestContext context(true);
3421 context.set_network_delegate(&network_delegate);
3422 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513423
3424 {
3425 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363426 scoped_ptr<URLRequest> r(
3427 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193428 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073429 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513430 HttpRequestHeaders headers;
3431 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513432 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193433 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563434
3435 // Quit after hitting the redirect, so can check the headers.
3436 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193437 r->Start();
[email protected]255620da2013-08-19 13:14:293438 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513439
[email protected]6be6fa92014-08-06 23:44:563440 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193441 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3442 EXPECT_EQ(307, r->GetResponseCode());
3443 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563444 std::string location;
[email protected]f7022f32014-08-21 16:32:193445 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3446 &location));
[email protected]6be6fa92014-08-06 23:44:563447 EXPECT_EQ(redirect_url, GURL(location));
3448
3449 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193450 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563451 base::RunLoop().Run();
3452
[email protected]f7022f32014-08-21 16:32:193453 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3454 EXPECT_EQ(0, r->status().error());
3455 EXPECT_EQ(redirect_url, r->url());
3456 EXPECT_EQ(original_url, r->original_url());
3457 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513458 EXPECT_EQ(1, network_delegate.created_requests());
3459 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193460 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513461 EXPECT_EQ(kData, d.data_received());
3462 }
3463 EXPECT_EQ(1, network_delegate.destroyed_requests());
3464}
3465
[email protected]5f714132014-03-26 10:41:163466// Tests that the network delegate can block and redirect a request to a new
3467// URL during OnHeadersReceived.
3468TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3469 ASSERT_TRUE(test_server_.Start());
3470
3471 TestDelegate d;
3472 BlockingNetworkDelegate network_delegate(
3473 BlockingNetworkDelegate::AUTO_CALLBACK);
3474 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3475 GURL redirect_url(test_server_.GetURL("simple.html"));
3476 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3477
3478 TestURLRequestContextWithProxy context(
3479 test_server_.host_port_pair().ToString(), &network_delegate);
3480
3481 {
3482 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363483 scoped_ptr<URLRequest> r(
3484 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163485
[email protected]f7022f32014-08-21 16:32:193486 r->Start();
[email protected]5f714132014-03-26 10:41:163487 base::RunLoop().Run();
3488
[email protected]f7022f32014-08-21 16:32:193489 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3490 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273491 EXPECT_EQ(
3492 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3493 EXPECT_TRUE(
3494 network_delegate.last_observed_proxy().Equals(
3495 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193496
3497 EXPECT_EQ(OK, r->status().error());
3498 EXPECT_EQ(redirect_url, r->url());
3499 EXPECT_EQ(original_url, r->original_url());
3500 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163501 EXPECT_EQ(2, network_delegate.created_requests());
3502 EXPECT_EQ(0, network_delegate.destroyed_requests());
3503 }
3504 EXPECT_EQ(1, network_delegate.destroyed_requests());
3505}
3506
[email protected]c2911d72011-10-03 22:16:363507// Tests that the network delegate can synchronously complete OnAuthRequired
3508// by taking no action. This indicates that the NetworkDelegate does not want to
3509// handle the challenge, and is passing the buck along to the
3510// URLRequest::Delegate.
3511TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3512 ASSERT_TRUE(test_server_.Start());
3513
3514 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303515 BlockingNetworkDelegate network_delegate(
3516 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363517
[email protected]ef2bf422012-05-11 03:27:093518 TestURLRequestContext context(true);
3519 context.set_network_delegate(&network_delegate);
3520 context.Init();
[email protected]c2911d72011-10-03 22:16:363521
[email protected]f3cf9802011-10-28 18:44:583522 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363523
3524 {
3525 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363526 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193527 r->Start();
[email protected]79e1fd62013-06-20 06:50:043528
[email protected]255620da2013-08-19 13:14:293529 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043530
[email protected]f7022f32014-08-21 16:32:193531 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3532 EXPECT_EQ(0, r->status().error());
3533 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043534 EXPECT_TRUE(d.auth_required_called());
3535 EXPECT_EQ(1, network_delegate.created_requests());
3536 EXPECT_EQ(0, network_delegate.destroyed_requests());
3537 }
3538 EXPECT_EQ(1, network_delegate.destroyed_requests());
3539}
3540
3541TEST_F(URLRequestTestHTTP,
3542 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3543 ASSERT_TRUE(test_server_.Start());
3544
3545 TestDelegate d;
3546 BlockingNetworkDelegate network_delegate(
3547 BlockingNetworkDelegate::SYNCHRONOUS);
3548
3549 TestURLRequestContext context(true);
3550 context.set_network_delegate(&network_delegate);
3551 context.Init();
3552
3553 d.set_credentials(AuthCredentials(kUser, kSecret));
3554
3555 {
3556 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363557 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193558 r->Start();
[email protected]79e1fd62013-06-20 06:50:043559
3560 {
3561 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193562 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043563 EXPECT_FALSE(headers.HasHeader("Authorization"));
3564 }
3565
[email protected]255620da2013-08-19 13:14:293566 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363567
[email protected]f7022f32014-08-21 16:32:193568 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3569 EXPECT_EQ(0, r->status().error());
3570 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363571 EXPECT_TRUE(d.auth_required_called());
3572 EXPECT_EQ(1, network_delegate.created_requests());
3573 EXPECT_EQ(0, network_delegate.destroyed_requests());
3574 }
3575 EXPECT_EQ(1, network_delegate.destroyed_requests());
3576}
3577
3578// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403579// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363580TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3581 ASSERT_TRUE(test_server_.Start());
3582
3583 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303584 BlockingNetworkDelegate network_delegate(
3585 BlockingNetworkDelegate::SYNCHRONOUS);
3586 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363587 network_delegate.set_auth_retval(
3588 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3589
[email protected]f3cf9802011-10-28 18:44:583590 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363591
[email protected]ef2bf422012-05-11 03:27:093592 TestURLRequestContext context(true);
3593 context.set_network_delegate(&network_delegate);
3594 context.Init();
[email protected]c2911d72011-10-03 22:16:363595
3596 {
3597 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363598 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193599 r->Start();
[email protected]255620da2013-08-19 13:14:293600 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363601
[email protected]f7022f32014-08-21 16:32:193602 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3603 EXPECT_EQ(0, r->status().error());
3604 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363605 EXPECT_FALSE(d.auth_required_called());
3606 EXPECT_EQ(1, network_delegate.created_requests());
3607 EXPECT_EQ(0, network_delegate.destroyed_requests());
3608 }
3609 EXPECT_EQ(1, network_delegate.destroyed_requests());
3610}
3611
[email protected]79e1fd62013-06-20 06:50:043612// Same as above, but also tests that GetFullRequestHeaders returns the proper
3613// headers (for the first or second request) when called at the proper times.
3614TEST_F(URLRequestTestHTTP,
3615 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3616 ASSERT_TRUE(test_server_.Start());
3617
3618 TestDelegate d;
3619 BlockingNetworkDelegate network_delegate(
3620 BlockingNetworkDelegate::SYNCHRONOUS);
3621 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3622 network_delegate.set_auth_retval(
3623 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3624
3625 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3626
3627 TestURLRequestContext context(true);
3628 context.set_network_delegate(&network_delegate);
3629 context.Init();
3630
3631 {
3632 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363633 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193634 r->Start();
[email protected]255620da2013-08-19 13:14:293635 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043636
[email protected]f7022f32014-08-21 16:32:193637 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3638 EXPECT_EQ(0, r->status().error());
3639 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043640 EXPECT_FALSE(d.auth_required_called());
3641 EXPECT_EQ(1, network_delegate.created_requests());
3642 EXPECT_EQ(0, network_delegate.destroyed_requests());
3643
3644 {
3645 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193646 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043647 EXPECT_TRUE(headers.HasHeader("Authorization"));
3648 }
3649 }
3650 EXPECT_EQ(1, network_delegate.destroyed_requests());
3651}
3652
[email protected]c2911d72011-10-03 22:16:363653// Tests that the network delegate can synchronously complete OnAuthRequired
3654// by cancelling authentication.
3655TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3656 ASSERT_TRUE(test_server_.Start());
3657
3658 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303659 BlockingNetworkDelegate network_delegate(
3660 BlockingNetworkDelegate::SYNCHRONOUS);
3661 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363662 network_delegate.set_auth_retval(
3663 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3664
[email protected]ef2bf422012-05-11 03:27:093665 TestURLRequestContext context(true);
3666 context.set_network_delegate(&network_delegate);
3667 context.Init();
[email protected]c2911d72011-10-03 22:16:363668
3669 {
3670 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363671 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193672 r->Start();
[email protected]255620da2013-08-19 13:14:293673 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363674
[email protected]f7022f32014-08-21 16:32:193675 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3676 EXPECT_EQ(OK, r->status().error());
3677 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363678 EXPECT_FALSE(d.auth_required_called());
3679 EXPECT_EQ(1, network_delegate.created_requests());
3680 EXPECT_EQ(0, network_delegate.destroyed_requests());
3681 }
3682 EXPECT_EQ(1, network_delegate.destroyed_requests());
3683}
3684
3685// Tests that the network delegate can asynchronously complete OnAuthRequired
3686// by taking no action. This indicates that the NetworkDelegate does not want
3687// to handle the challenge, and is passing the buck along to the
3688// URLRequest::Delegate.
3689TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3690 ASSERT_TRUE(test_server_.Start());
3691
3692 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303693 BlockingNetworkDelegate network_delegate(
3694 BlockingNetworkDelegate::AUTO_CALLBACK);
3695 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363696
[email protected]ef2bf422012-05-11 03:27:093697 TestURLRequestContext context(true);
3698 context.set_network_delegate(&network_delegate);
3699 context.Init();
[email protected]c2911d72011-10-03 22:16:363700
[email protected]f3cf9802011-10-28 18:44:583701 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363702
3703 {
3704 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363705 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193706 r->Start();
[email protected]255620da2013-08-19 13:14:293707 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363708
[email protected]f7022f32014-08-21 16:32:193709 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3710 EXPECT_EQ(0, r->status().error());
3711 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363712 EXPECT_TRUE(d.auth_required_called());
3713 EXPECT_EQ(1, network_delegate.created_requests());
3714 EXPECT_EQ(0, network_delegate.destroyed_requests());
3715 }
3716 EXPECT_EQ(1, network_delegate.destroyed_requests());
3717}
3718
3719// Tests that the network delegate can asynchronously complete OnAuthRequired
3720// by setting credentials.
3721TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3722 ASSERT_TRUE(test_server_.Start());
3723
3724 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303725 BlockingNetworkDelegate network_delegate(
3726 BlockingNetworkDelegate::AUTO_CALLBACK);
3727 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363728 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363729 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3730
[email protected]f3cf9802011-10-28 18:44:583731 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363732 network_delegate.set_auth_credentials(auth_credentials);
3733
[email protected]ef2bf422012-05-11 03:27:093734 TestURLRequestContext context(true);
3735 context.set_network_delegate(&network_delegate);
3736 context.Init();
[email protected]c2911d72011-10-03 22:16:363737
3738 {
3739 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363740 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193741 r->Start();
[email protected]255620da2013-08-19 13:14:293742 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363743
[email protected]f7022f32014-08-21 16:32:193744 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3745 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:363746
[email protected]f7022f32014-08-21 16:32:193747 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363748 EXPECT_FALSE(d.auth_required_called());
3749 EXPECT_EQ(1, network_delegate.created_requests());
3750 EXPECT_EQ(0, network_delegate.destroyed_requests());
3751 }
3752 EXPECT_EQ(1, network_delegate.destroyed_requests());
3753}
3754
3755// Tests that the network delegate can asynchronously complete OnAuthRequired
3756// by cancelling authentication.
3757TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3758 ASSERT_TRUE(test_server_.Start());
3759
3760 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303761 BlockingNetworkDelegate network_delegate(
3762 BlockingNetworkDelegate::AUTO_CALLBACK);
3763 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363764 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363765 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3766
[email protected]ef2bf422012-05-11 03:27:093767 TestURLRequestContext context(true);
3768 context.set_network_delegate(&network_delegate);
3769 context.Init();
[email protected]c2911d72011-10-03 22:16:363770
3771 {
3772 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363773 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193774 r->Start();
[email protected]255620da2013-08-19 13:14:293775 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363776
[email protected]f7022f32014-08-21 16:32:193777 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3778 EXPECT_EQ(OK, r->status().error());
3779 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363780 EXPECT_FALSE(d.auth_required_called());
3781 EXPECT_EQ(1, network_delegate.created_requests());
3782 EXPECT_EQ(0, network_delegate.destroyed_requests());
3783 }
3784 EXPECT_EQ(1, network_delegate.destroyed_requests());
3785}
3786
[email protected]9045b8822012-01-13 20:35:353787// Tests that we can handle when a network request was canceled while we were
3788// waiting for the network delegate.
3789// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3790TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3791 ASSERT_TRUE(test_server_.Start());
3792
3793 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303794 BlockingNetworkDelegate network_delegate(
3795 BlockingNetworkDelegate::USER_CALLBACK);
3796 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353797
[email protected]ef2bf422012-05-11 03:27:093798 TestURLRequestContext context(true);
3799 context.set_network_delegate(&network_delegate);
3800 context.Init();
[email protected]9045b8822012-01-13 20:35:353801
3802 {
[email protected]f7022f32014-08-21 16:32:193803 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363804 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353805
[email protected]f7022f32014-08-21 16:32:193806 r->Start();
[email protected]255620da2013-08-19 13:14:293807 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303808 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3809 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353810 EXPECT_EQ(0, network_delegate.completed_requests());
3811 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193812 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353813 // Ensure that network delegate is notified.
3814 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193815 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3816 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353817 EXPECT_EQ(1, network_delegate.created_requests());
3818 EXPECT_EQ(0, network_delegate.destroyed_requests());
3819 }
3820 EXPECT_EQ(1, network_delegate.destroyed_requests());
3821}
3822
3823// Tests that we can handle when a network request was canceled while we were
3824// waiting for the network delegate.
3825// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3826TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3827 ASSERT_TRUE(test_server_.Start());
3828
3829 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303830 BlockingNetworkDelegate network_delegate(
3831 BlockingNetworkDelegate::USER_CALLBACK);
3832 network_delegate.set_block_on(
3833 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:353834
[email protected]ef2bf422012-05-11 03:27:093835 TestURLRequestContext context(true);
3836 context.set_network_delegate(&network_delegate);
3837 context.Init();
[email protected]9045b8822012-01-13 20:35:353838
3839 {
[email protected]f7022f32014-08-21 16:32:193840 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363841 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353842
[email protected]f7022f32014-08-21 16:32:193843 r->Start();
[email protected]255620da2013-08-19 13:14:293844 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303845 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3846 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353847 EXPECT_EQ(0, network_delegate.completed_requests());
3848 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193849 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353850 // Ensure that network delegate is notified.
3851 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193852 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3853 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353854 EXPECT_EQ(1, network_delegate.created_requests());
3855 EXPECT_EQ(0, network_delegate.destroyed_requests());
3856 }
3857 EXPECT_EQ(1, network_delegate.destroyed_requests());
3858}
3859
3860// Tests that we can handle when a network request was canceled while we were
3861// waiting for the network delegate.
3862// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3863TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3864 ASSERT_TRUE(test_server_.Start());
3865
3866 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303867 BlockingNetworkDelegate network_delegate(
3868 BlockingNetworkDelegate::USER_CALLBACK);
3869 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:353870
[email protected]ef2bf422012-05-11 03:27:093871 TestURLRequestContext context(true);
3872 context.set_network_delegate(&network_delegate);
3873 context.Init();
[email protected]9045b8822012-01-13 20:35:353874
3875 {
[email protected]f7022f32014-08-21 16:32:193876 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363877 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353878
[email protected]f7022f32014-08-21 16:32:193879 r->Start();
[email protected]255620da2013-08-19 13:14:293880 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303881 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3882 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353883 EXPECT_EQ(0, network_delegate.completed_requests());
3884 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193885 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353886 // Ensure that network delegate is notified.
3887 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193888 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3889 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353890 EXPECT_EQ(1, network_delegate.created_requests());
3891 EXPECT_EQ(0, network_delegate.destroyed_requests());
3892 }
3893 EXPECT_EQ(1, network_delegate.destroyed_requests());
3894}
3895
3896// Tests that we can handle when a network request was canceled while we were
3897// waiting for the network delegate.
3898// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:023899TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:353900 ASSERT_TRUE(test_server_.Start());
3901
3902 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303903 BlockingNetworkDelegate network_delegate(
3904 BlockingNetworkDelegate::USER_CALLBACK);
3905 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:353906
[email protected]ef2bf422012-05-11 03:27:093907 TestURLRequestContext context(true);
3908 context.set_network_delegate(&network_delegate);
3909 context.Init();
[email protected]9045b8822012-01-13 20:35:353910
3911 {
[email protected]f7022f32014-08-21 16:32:193912 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363913 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353914
[email protected]f7022f32014-08-21 16:32:193915 r->Start();
[email protected]255620da2013-08-19 13:14:293916 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303917 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3918 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353919 EXPECT_EQ(0, network_delegate.completed_requests());
3920 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193921 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353922 // Ensure that network delegate is notified.
3923 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193924 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3925 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353926 EXPECT_EQ(1, network_delegate.created_requests());
3927 EXPECT_EQ(0, network_delegate.destroyed_requests());
3928 }
3929 EXPECT_EQ(1, network_delegate.destroyed_requests());
3930}
3931
[email protected]95409e12010-08-17 20:07:113932// In this unit test, we're using the HTTPTestServer as a proxy server and
3933// issuing a CONNECT request with the magic host name "www.server-auth.com".
3934// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:353935TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:113936 ASSERT_TRUE(test_server_.Start());
3937
[email protected]ceefd7fd2012-11-29 00:36:243938 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043939 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193940 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503941
[email protected]dc651782009-02-14 01:45:083942 TestDelegate d;
3943 {
[email protected]f7022f32014-08-21 16:32:193944 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363945 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:083946
[email protected]f7022f32014-08-21 16:32:193947 r->Start();
3948 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:083949
[email protected]255620da2013-08-19 13:14:293950 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:083951
[email protected]f7022f32014-08-21 16:32:193952 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153953 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193954 EXPECT_TRUE(r->proxy_server().IsEmpty());
3955 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083956 }
3957}
3958
[email protected]b89290212009-08-14 22:37:353959TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:113960 ASSERT_TRUE(test_server_.Start());
3961
initial.commit586acc5fe2008-07-26 22:42:523962 TestDelegate d;
3963 {
[email protected]f7022f32014-08-21 16:32:193964 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363965 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:523966
[email protected]f7022f32014-08-21 16:32:193967 r->Start();
3968 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:523969
[email protected]255620da2013-08-19 13:14:293970 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523971
3972 EXPECT_EQ(1, d.response_started_count());
3973 EXPECT_FALSE(d.received_data_before_response());
3974 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193975 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193976 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:193977 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193978 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:163979
[email protected]9e743cd2010-03-16 07:03:533980 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:523981 }
initial.commit586acc5fe2008-07-26 22:42:523982}
3983
[email protected]263163f2012-06-14 22:40:343984// This test has the server send a large number of cookies to the client.
3985// To ensure that no number of cookies causes a crash, a galloping binary
3986// search is used to estimate that maximum number of cookies that are accepted
3987// by the browser. Beyond the maximum number, the request will fail with
3988// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:303989#if defined(OS_WIN)
3990// http://crbug.com/177916
3991#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3992#else
3993#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3994#endif // defined(OS_WIN)
3995TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:343996 ASSERT_TRUE(test_server_.Start());
3997
3998 int lower_bound = 0;
3999 int upper_bound = 1;
4000
4001 // Double the number of cookies until the response header limits are
4002 // exceeded.
4003 while (DoManyCookiesRequest(upper_bound)) {
4004 lower_bound = upper_bound;
4005 upper_bound *= 2;
4006 ASSERT_LT(upper_bound, 1000000);
4007 }
4008
pkasting6b68a162014-12-01 22:10:294009 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344010 if (tolerance < 2)
4011 tolerance = 2;
4012
4013 // Perform a binary search to find the highest possible number of cookies,
4014 // within the desired tolerance.
4015 while (upper_bound - lower_bound >= tolerance) {
4016 int num_cookies = (lower_bound + upper_bound) / 2;
4017
4018 if (DoManyCookiesRequest(num_cookies))
4019 lower_bound = num_cookies;
4020 else
4021 upper_bound = num_cookies;
4022 }
4023 // Success: the test did not crash.
4024}
4025
[email protected]b89290212009-08-14 22:37:354026TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:114027 ASSERT_TRUE(test_server_.Start());
4028
initial.commit586acc5fe2008-07-26 22:42:524029 TestDelegate d;
4030 {
[email protected]f7022f32014-08-21 16:32:194031 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364032 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524033
[email protected]f7022f32014-08-21 16:32:194034 r->Start();
4035 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524036
[email protected]255620da2013-08-19 13:14:294037 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524038
4039 EXPECT_EQ(1, d.response_started_count());
4040 EXPECT_FALSE(d.received_data_before_response());
4041 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:194042 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194043 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:194044 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194045 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524046 }
[email protected]5d7b373e2009-09-02 07:19:034047}
4048
[email protected]79e1fd62013-06-20 06:50:044049TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
4050 ASSERT_TRUE(test_server_.Start());
4051
4052 TestDelegate d;
4053 {
4054 GURL test_url(test_server_.GetURL(std::string()));
davidben151423e2015-03-23 18:48:364055 scoped_ptr<URLRequest> r(
4056 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044057
4058 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194059 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044060
[email protected]f7022f32014-08-21 16:32:194061 r->Start();
4062 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044063
[email protected]255620da2013-08-19 13:14:294064 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044065
4066 EXPECT_EQ(1, d.response_started_count());
4067 EXPECT_FALSE(d.received_data_before_response());
4068 EXPECT_NE(0, d.bytes_received());
4069 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194070 r->GetSocketAddress().host());
[email protected]79e1fd62013-06-20 06:50:044071 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194072 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044073
4074 EXPECT_TRUE(d.have_full_request_headers());
4075 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4076 }
4077}
4078
[email protected]58e32bb2013-01-21 18:23:254079TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
4080 ASSERT_TRUE(test_server_.Start());
4081
4082 TestDelegate d;
4083 {
[email protected]f7022f32014-08-21 16:32:194084 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364085 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254086
[email protected]f7022f32014-08-21 16:32:194087 r->Start();
4088 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254089
[email protected]255620da2013-08-19 13:14:294090 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254091
4092 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194093 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254094 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4095
4096 EXPECT_EQ(1, d.response_started_count());
4097 EXPECT_FALSE(d.received_data_before_response());
4098 EXPECT_NE(0, d.bytes_received());
4099 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194100 r->GetSocketAddress().host());
[email protected]58e32bb2013-01-21 18:23:254101 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194102 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254103 }
4104}
4105
[email protected]aad63572011-05-24 20:14:394106TEST_F(URLRequestTestHTTP, GetZippedTest) {
4107 ASSERT_TRUE(test_server_.Start());
4108
4109 // Parameter that specifies the Content-Length field in the response:
4110 // C - Compressed length.
4111 // U - Uncompressed length.
4112 // L - Large length (larger than both C & U).
4113 // M - Medium length (between C & U).
4114 // S - Small length (smaller than both C & U).
4115 const char test_parameters[] = "CULMS";
4116 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4117 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444118 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394119 // S has too little data, but we seem to accept it.
4120 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374121 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394122
4123 for (int i = 0; i < num_tests ; i++) {
4124 TestDelegate d;
4125 {
4126 std::string test_file =
4127 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
4128 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394129
[email protected]ceefd7fd2012-11-29 00:36:244130 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094131 TestURLRequestContext context(true);
4132 context.set_network_delegate(&network_delegate);
4133 context.Init();
[email protected]87a09a92011-07-14 15:50:504134
[email protected]f7022f32014-08-21 16:32:194135 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364136 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194137 r->Start();
4138 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394139
[email protected]255620da2013-08-19 13:14:294140 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394141
4142 EXPECT_EQ(1, d.response_started_count());
4143 EXPECT_FALSE(d.received_data_before_response());
4144 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194145 << " status = " << r->status().status()
4146 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394147 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194148 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394149 << " Parameter = \"" << test_file << "\"";
4150 } else {
[email protected]f7022f32014-08-21 16:32:194151 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4152 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394153 << " Parameter = \"" << test_file << "\"";
4154 }
4155 }
4156 }
4157}
4158
tbansala1caf9612015-06-01 20:24:184159TEST_F(URLRequestTestHTTP, NetworkQualityEstimator) {
tbansalea2fb8c2015-05-22 22:23:004160 ASSERT_TRUE(test_server_.Start());
4161 // Enable requests to local host to be used for network quality estimation.
tbansalb177b5392015-06-25 11:13:024162 std::map<std::string, std::string> variation_params;
tbansal1c92d5b2015-08-14 20:14:434163 NetworkQualityEstimator estimator(scoped_ptr<net::ExternalEstimateProvider>(),
4164 variation_params, true, true);
tbansalea2fb8c2015-05-22 22:23:004165
4166 TestDelegate d;
4167 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4168 TestURLRequestContext context(true);
4169 context.set_network_quality_estimator(&estimator);
4170 context.set_network_delegate(&network_delegate);
4171 context.Init();
4172
tbansalafc2c1cb2015-06-15 23:58:594173 std::string url = "echo.html";
tbansalea2fb8c2015-05-22 22:23:004174
4175 scoped_ptr<URLRequest> r(
4176 context.CreateRequest(test_server_.GetURL(url), DEFAULT_PRIORITY, &d));
tbansalea2fb8c2015-05-22 22:23:004177 r->Start();
4178
4179 base::RunLoop().Run();
4180
tbansal9533b6f2015-08-11 22:06:084181 base::TimeDelta rtt;
4182 int32_t kbps;
4183 EXPECT_TRUE(estimator.GetRTTEstimate(&rtt));
4184 EXPECT_TRUE(estimator.GetDownlinkThroughputKbpsEstimate(&kbps));
4185 EXPECT_GE(rtt, base::TimeDelta());
4186 EXPECT_LT(rtt, base::TimeDelta::Max());
4187 EXPECT_GT(kbps, 0);
tbansalea2fb8c2015-05-22 22:23:004188
4189 // Verify that histograms are not populated. They should populate only when
4190 // there is a change in ConnectionType.
4191 base::HistogramTester histogram_tester;
4192 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 0);
4193 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 0);
4194
4195 NetworkChangeNotifier::NotifyObserversOfConnectionTypeChangeForTests(
4196 NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI);
4197 base::MessageLoop::current()->RunUntilIdle();
4198 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 1);
4199 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 1);
4200}
4201
[email protected]58e32bb2013-01-21 18:23:254202TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
4203 ASSERT_TRUE(test_server_.Start());
4204
[email protected]007b3f82013-04-09 08:46:454205 GURL destination_url = test_server_.GetURL(std::string());
4206 GURL original_url =
4207 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254208 TestDelegate d;
davidben151423e2015-03-23 18:48:364209 scoped_ptr<URLRequest> req(
4210 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194211 req->Start();
[email protected]255620da2013-08-19 13:14:294212 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254213
4214 EXPECT_EQ(1, d.response_started_count());
4215 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194216 EXPECT_EQ(destination_url, req->url());
4217 EXPECT_EQ(original_url, req->original_url());
4218 ASSERT_EQ(2U, req->url_chain().size());
4219 EXPECT_EQ(original_url, req->url_chain()[0]);
4220 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254221
4222 LoadTimingInfo load_timing_info_before_redirect;
4223 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4224 &load_timing_info_before_redirect));
4225 TestLoadTimingNotReused(load_timing_info_before_redirect,
4226 CONNECT_TIMING_HAS_DNS_TIMES);
4227
4228 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194229 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254230 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4231
4232 // Check that a new socket was used on redirect, since the server does not
4233 // supposed keep-alive sockets, and that the times before the redirect are
4234 // before the ones recorded for the second request.
4235 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4236 load_timing_info.socket_log_id);
4237 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4238 load_timing_info.connect_timing.connect_start);
4239}
4240
[email protected]8f1ac082011-04-19 21:14:134241TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
4242 ASSERT_TRUE(test_server_.Start());
4243
[email protected]007b3f82013-04-09 08:46:454244 GURL destination_url = test_server_.GetURL(std::string());
4245 GURL middle_redirect_url =
4246 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:134247 GURL original_url = test_server_.GetURL(
4248 "server-redirect?" + middle_redirect_url.spec());
4249 TestDelegate d;
davidben151423e2015-03-23 18:48:364250 scoped_ptr<URLRequest> req(
4251 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194252 req->Start();
[email protected]255620da2013-08-19 13:14:294253 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134254
4255 EXPECT_EQ(1, d.response_started_count());
4256 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194257 EXPECT_EQ(destination_url, req->url());
4258 EXPECT_EQ(original_url, req->original_url());
4259 ASSERT_EQ(3U, req->url_chain().size());
4260 EXPECT_EQ(original_url, req->url_chain()[0]);
4261 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4262 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134263}
4264
[email protected]abe1c4a2013-10-25 19:28:514265// First and second pieces of information logged by delegates to URLRequests.
4266const char kFirstDelegateInfo[] = "Wonderful delegate";
4267const char kSecondDelegateInfo[] = "Exciting delegate";
4268
4269// Logs delegate information to a URLRequest. The first string is logged
4270// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4271// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4272// another asynchronous call is used to clear the delegate information
4273// before calling a callback. The object then deletes itself.
4274class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4275 public:
4276 typedef base::Callback<void()> Callback;
4277
4278 // Each time delegate information is added to the URLRequest, the resulting
4279 // load state is checked. The expected load state after each request is
4280 // passed in as an argument.
4281 static void Run(URLRequest* url_request,
4282 LoadState expected_first_load_state,
4283 LoadState expected_second_load_state,
4284 LoadState expected_third_load_state,
4285 const Callback& callback) {
4286 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4287 url_request,
4288 expected_first_load_state,
4289 expected_second_load_state,
4290 expected_third_load_state,
4291 callback);
4292 logger->Start();
4293 }
4294
4295 // Checks that the log entries, starting with log_position, contain the
4296 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4297 // recorded. Returns the index of entry after the expected number of
4298 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464299 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514300 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514301 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4302 if (log_position + 3 >= entries.size()) {
4303 ADD_FAILURE() << "Not enough log entries";
4304 return entries.size();
4305 }
4306 std::string delegate_info;
4307 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4308 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4309 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4310 &delegate_info));
4311 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4312
4313 ++log_position;
4314 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4315 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4316
4317 ++log_position;
4318 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4319 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4320 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4321 &delegate_info));
4322 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4323
4324 ++log_position;
4325 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4326 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4327
4328 return log_position + 1;
4329 }
4330
[email protected]1826a402014-01-08 15:40:484331 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4332 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464333 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4334 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484335 log_position =
4336 ExpectLogContainsSomewhereAfter(entries,
4337 log_position,
4338 NetLog::TYPE_URL_REQUEST_DELEGATE,
4339 NetLog::PHASE_BEGIN);
4340 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4341 entries[log_position + 1].type);
4342 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4343 return log_position + 1;
4344 }
4345
[email protected]abe1c4a2013-10-25 19:28:514346 private:
4347 friend class base::RefCounted<AsyncDelegateLogger>;
4348
4349 AsyncDelegateLogger(URLRequest* url_request,
4350 LoadState expected_first_load_state,
4351 LoadState expected_second_load_state,
4352 LoadState expected_third_load_state,
4353 const Callback& callback)
4354 : url_request_(url_request),
4355 expected_first_load_state_(expected_first_load_state),
4356 expected_second_load_state_(expected_second_load_state),
4357 expected_third_load_state_(expected_third_load_state),
4358 callback_(callback) {
4359 }
4360
4361 ~AsyncDelegateLogger() {}
4362
4363 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534364 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514365 LoadStateWithParam load_state = url_request_->GetLoadState();
4366 EXPECT_EQ(expected_first_load_state_, load_state.state);
4367 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454368 base::ThreadTaskRunnerHandle::Get()->PostTask(
4369 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514370 }
4371
4372 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534373 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514374 LoadStateWithParam load_state = url_request_->GetLoadState();
4375 EXPECT_EQ(expected_second_load_state_, load_state.state);
4376 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4377 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4378 } else {
4379 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4380 }
skyostil4891b25b2015-06-11 11:43:454381 base::ThreadTaskRunnerHandle::Get()->PostTask(
4382 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514383 }
4384
4385 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534386 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514387 LoadStateWithParam load_state = url_request_->GetLoadState();
4388 EXPECT_EQ(expected_third_load_state_, load_state.state);
4389 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084390 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514391 callback_.Run();
4392 }
4393
4394 URLRequest* url_request_;
4395 const int expected_first_load_state_;
4396 const int expected_second_load_state_;
4397 const int expected_third_load_state_;
4398 const Callback callback_;
4399
4400 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4401};
4402
4403// NetworkDelegate that logs delegate information before a request is started,
4404// before headers are sent, when headers are read, and when auth information
4405// is requested. Uses AsyncDelegateLogger.
4406class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4407 public:
4408 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204409 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514410
4411 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204412 int OnBeforeURLRequest(URLRequest* request,
4413 const CompletionCallback& callback,
4414 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514415 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4416 return RunCallbackAsynchronously(request, callback);
4417 }
4418
dchengb03027d2014-10-21 12:00:204419 int OnBeforeSendHeaders(URLRequest* request,
4420 const CompletionCallback& callback,
4421 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514422 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4423 return RunCallbackAsynchronously(request, callback);
4424 }
4425
dchengb03027d2014-10-21 12:00:204426 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514427 URLRequest* request,
4428 const CompletionCallback& callback,
4429 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164430 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134431 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164432 TestNetworkDelegate::OnHeadersReceived(request,
4433 callback,
[email protected]abe1c4a2013-10-25 19:28:514434 original_response_headers,
[email protected]5f714132014-03-26 10:41:164435 override_response_headers,
4436 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514437 return RunCallbackAsynchronously(request, callback);
4438 }
4439
dchengb03027d2014-10-21 12:00:204440 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514441 URLRequest* request,
4442 const AuthChallengeInfo& auth_info,
4443 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134444 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514445 AsyncDelegateLogger::Run(
4446 request,
4447 LOAD_STATE_WAITING_FOR_DELEGATE,
4448 LOAD_STATE_WAITING_FOR_DELEGATE,
4449 LOAD_STATE_WAITING_FOR_DELEGATE,
4450 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4451 callback, credentials));
4452 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4453 }
4454
4455 private:
4456 static int RunCallbackAsynchronously(
4457 URLRequest* request,
4458 const CompletionCallback& callback) {
4459 AsyncDelegateLogger::Run(
4460 request,
4461 LOAD_STATE_WAITING_FOR_DELEGATE,
4462 LOAD_STATE_WAITING_FOR_DELEGATE,
4463 LOAD_STATE_WAITING_FOR_DELEGATE,
4464 base::Bind(callback, OK));
4465 return ERR_IO_PENDING;
4466 }
4467
4468 static void SetAuthAndResume(const AuthCallback& callback,
4469 AuthCredentials* credentials) {
4470 *credentials = AuthCredentials(kUser, kSecret);
4471 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4472 }
4473
4474 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4475};
4476
4477// URLRequest::Delegate that logs delegate information when the headers
4478// are received, when each read completes, and during redirects. Uses
4479// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4480//
4481// Inherits from TestDelegate to reuse the TestDelegate code to handle
4482// advancing to the next step in most cases, as well as cancellation.
4483class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4484 public:
4485 enum CancelStage {
4486 NO_CANCEL = 0,
4487 CANCEL_ON_RECEIVED_REDIRECT,
4488 CANCEL_ON_RESPONSE_STARTED,
4489 CANCEL_ON_READ_COMPLETED
4490 };
4491
4492 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4493 : cancel_stage_(cancel_stage) {
4494 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4495 set_cancel_in_received_redirect(true);
4496 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4497 set_cancel_in_response_started(true);
4498 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4499 set_cancel_in_received_data(true);
4500 }
dchengb03027d2014-10-21 12:00:204501 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514502
4503 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204504 void OnReceivedRedirect(URLRequest* request,
4505 const RedirectInfo& redirect_info,
4506 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514507 *defer_redirect = true;
4508 AsyncDelegateLogger::Run(
4509 request,
4510 LOAD_STATE_WAITING_FOR_DELEGATE,
4511 LOAD_STATE_WAITING_FOR_DELEGATE,
4512 LOAD_STATE_WAITING_FOR_DELEGATE,
4513 base::Bind(
4514 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594515 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514516 }
4517
dchengb03027d2014-10-21 12:00:204518 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514519 AsyncDelegateLogger::Run(
4520 request,
4521 LOAD_STATE_WAITING_FOR_DELEGATE,
4522 LOAD_STATE_WAITING_FOR_DELEGATE,
4523 LOAD_STATE_WAITING_FOR_DELEGATE,
4524 base::Bind(
4525 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4526 base::Unretained(this), request));
4527 }
4528
dchengb03027d2014-10-21 12:00:204529 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514530 AsyncDelegateLogger::Run(
4531 request,
4532 LOAD_STATE_IDLE,
4533 LOAD_STATE_IDLE,
4534 LOAD_STATE_IDLE,
4535 base::Bind(
4536 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4537 base::Unretained(this), request, bytes_read));
4538 }
4539
4540 private:
4541 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594542 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514543 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594544 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514545 // FollowDeferredRedirect should not be called after cancellation.
4546 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4547 return;
4548 if (!defer_redirect)
4549 request->FollowDeferredRedirect();
4550 }
4551
4552 void OnResponseStartedLoggingComplete(URLRequest* request) {
4553 // The parent class continues the request.
4554 TestDelegate::OnResponseStarted(request);
4555 }
4556
4557 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4558 // The parent class continues the request.
4559 TestDelegate::OnReadCompleted(request, bytes_read);
4560 }
4561
4562 const CancelStage cancel_stage_;
4563
4564 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4565};
4566
4567// Tests handling of delegate info before a request starts.
4568TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4569 ASSERT_TRUE(test_server_.Start());
4570
4571 TestDelegate request_delegate;
4572 TestURLRequestContext context(true);
4573 context.set_network_delegate(NULL);
4574 context.set_net_log(&net_log_);
4575 context.Init();
4576
4577 {
davidben151423e2015-03-23 18:48:364578 scoped_ptr<URLRequest> r(
4579 context.CreateRequest(test_server_.GetURL("empty.html"),
4580 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194581 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514582 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084583 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514584
4585 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194586 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514587 LOAD_STATE_WAITING_FOR_DELEGATE,
4588 LOAD_STATE_WAITING_FOR_DELEGATE,
4589 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194590 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514591
4592 base::RunLoop().Run();
4593
[email protected]f7022f32014-08-21 16:32:194594 EXPECT_EQ(200, r->GetResponseCode());
4595 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514596 }
4597
mmenke43758e62015-05-04 21:09:464598 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514599 net_log_.GetEntries(&entries);
4600 size_t log_position = ExpectLogContainsSomewhereAfter(
4601 entries,
4602 0,
4603 NetLog::TYPE_DELEGATE_INFO,
4604 NetLog::PHASE_BEGIN);
4605
4606 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4607
4608 // Nothing else should add any delegate info to the request.
4609 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4610 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4611}
4612
4613// Tests handling of delegate info from a network delegate.
4614TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4615 ASSERT_TRUE(test_server_.Start());
4616
4617 TestDelegate request_delegate;
4618 AsyncLoggingNetworkDelegate network_delegate;
4619 TestURLRequestContext context(true);
4620 context.set_network_delegate(&network_delegate);
4621 context.set_net_log(&net_log_);
4622 context.Init();
4623
4624 {
davidben151423e2015-03-23 18:48:364625 scoped_ptr<URLRequest> r(
4626 context.CreateRequest(test_server_.GetURL("simple.html"),
4627 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194628 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514629 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084630 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514631
[email protected]f7022f32014-08-21 16:32:194632 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514633 base::RunLoop().Run();
4634
[email protected]f7022f32014-08-21 16:32:194635 EXPECT_EQ(200, r->GetResponseCode());
4636 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514637 EXPECT_EQ(1, network_delegate.created_requests());
4638 EXPECT_EQ(0, network_delegate.destroyed_requests());
4639 }
4640 EXPECT_EQ(1, network_delegate.destroyed_requests());
4641
4642 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464643 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514644 net_log_.GetEntries(&entries);
4645 for (size_t i = 0; i < 3; ++i) {
4646 log_position = ExpectLogContainsSomewhereAfter(
4647 entries,
4648 log_position + 1,
4649 NetLog::TYPE_URL_REQUEST_DELEGATE,
4650 NetLog::PHASE_BEGIN);
4651
4652 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4653 log_position + 1);
4654
4655 ASSERT_LT(log_position, entries.size());
4656 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4657 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484658
4659 if (i == 1) {
4660 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4661 entries, log_position + 1);
4662 }
[email protected]abe1c4a2013-10-25 19:28:514663 }
4664
4665 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4666 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4667}
4668
4669// Tests handling of delegate info from a network delegate in the case of an
4670// HTTP redirect.
4671TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4672 ASSERT_TRUE(test_server_.Start());
4673
4674 TestDelegate request_delegate;
4675 AsyncLoggingNetworkDelegate network_delegate;
4676 TestURLRequestContext context(true);
4677 context.set_network_delegate(&network_delegate);
4678 context.set_net_log(&net_log_);
4679 context.Init();
4680
4681 {
[email protected]f7022f32014-08-21 16:32:194682 scoped_ptr<URLRequest> r(context.CreateRequest(
4683 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364684 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194685 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514686 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084687 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514688
[email protected]f7022f32014-08-21 16:32:194689 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514690 base::RunLoop().Run();
4691
[email protected]f7022f32014-08-21 16:32:194692 EXPECT_EQ(200, r->GetResponseCode());
4693 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514694 EXPECT_EQ(2, network_delegate.created_requests());
4695 EXPECT_EQ(0, network_delegate.destroyed_requests());
4696 }
4697 EXPECT_EQ(1, network_delegate.destroyed_requests());
4698
4699 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464700 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514701 net_log_.GetEntries(&entries);
4702 // The NetworkDelegate logged information in OnBeforeURLRequest,
4703 // OnBeforeSendHeaders, and OnHeadersReceived.
4704 for (size_t i = 0; i < 3; ++i) {
4705 log_position = ExpectLogContainsSomewhereAfter(
4706 entries,
4707 log_position + 1,
4708 NetLog::TYPE_URL_REQUEST_DELEGATE,
4709 NetLog::PHASE_BEGIN);
4710
4711 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4712 log_position + 1);
4713
4714 ASSERT_LT(log_position, entries.size());
4715 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4716 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484717
4718 if (i == 1) {
4719 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4720 entries, log_position + 1);
4721 }
[email protected]abe1c4a2013-10-25 19:28:514722 }
4723
4724 // The URLRequest::Delegate then gets informed about the redirect.
4725 log_position = ExpectLogContainsSomewhereAfter(
4726 entries,
4727 log_position + 1,
4728 NetLog::TYPE_URL_REQUEST_DELEGATE,
4729 NetLog::PHASE_BEGIN);
4730
4731 // The NetworkDelegate logged information in the same three events as before.
4732 for (size_t i = 0; i < 3; ++i) {
4733 log_position = ExpectLogContainsSomewhereAfter(
4734 entries,
4735 log_position + 1,
4736 NetLog::TYPE_URL_REQUEST_DELEGATE,
4737 NetLog::PHASE_BEGIN);
4738
4739 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4740 log_position + 1);
4741
4742 ASSERT_LT(log_position, entries.size());
4743 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4744 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4745 }
4746
4747 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4748 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4749}
4750
4751// Tests handling of delegate info from a network delegate in the case of HTTP
4752// AUTH.
4753TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4754 ASSERT_TRUE(test_server_.Start());
4755
4756 TestDelegate request_delegate;
4757 AsyncLoggingNetworkDelegate network_delegate;
4758 TestURLRequestContext context(true);
4759 context.set_network_delegate(&network_delegate);
4760 context.set_net_log(&net_log_);
4761 context.Init();
4762
4763 {
davidben151423e2015-03-23 18:48:364764 scoped_ptr<URLRequest> r(
4765 context.CreateRequest(test_server_.GetURL("auth-basic"),
4766 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194767 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514768 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084769 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514770
[email protected]f7022f32014-08-21 16:32:194771 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514772 base::RunLoop().Run();
4773
[email protected]f7022f32014-08-21 16:32:194774 EXPECT_EQ(200, r->GetResponseCode());
4775 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514776 EXPECT_EQ(1, network_delegate.created_requests());
4777 EXPECT_EQ(0, network_delegate.destroyed_requests());
4778 }
4779 EXPECT_EQ(1, network_delegate.destroyed_requests());
4780
4781 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464782 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514783 net_log_.GetEntries(&entries);
4784 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4785 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4786 // OnBeforeURLRequest and OnBeforeSendHeaders.
4787 for (size_t i = 0; i < 6; ++i) {
4788 log_position = ExpectLogContainsSomewhereAfter(
4789 entries,
4790 log_position + 1,
4791 NetLog::TYPE_URL_REQUEST_DELEGATE,
4792 NetLog::PHASE_BEGIN);
4793
4794 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4795 log_position + 1);
4796
4797 ASSERT_LT(log_position, entries.size());
4798 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4799 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484800
4801 if (i == 1) {
4802 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4803 entries, log_position + 1);
4804 }
[email protected]abe1c4a2013-10-25 19:28:514805 }
4806
4807 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4808 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4809}
4810
4811// Tests handling of delegate info from a URLRequest::Delegate.
4812TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4813 ASSERT_TRUE(test_server_.Start());
4814
4815 AsyncLoggingUrlRequestDelegate request_delegate(
4816 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4817 TestURLRequestContext context(true);
4818 context.set_network_delegate(NULL);
4819 context.set_net_log(&net_log_);
4820 context.Init();
4821
4822 {
4823 // A chunked response with delays between chunks is used to make sure that
4824 // attempts by the URLRequest delegate to log information while reading the
4825 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:484826 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:514827 // that it occurs.
[email protected]f7022f32014-08-21 16:32:194828 scoped_ptr<URLRequest> r(context.CreateRequest(
4829 test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364830 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194831 LoadStateWithParam load_state = r->GetLoadState();
4832 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514833 base::RunLoop().Run();
4834
[email protected]f7022f32014-08-21 16:32:194835 EXPECT_EQ(200, r->GetResponseCode());
4836 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514837 }
4838
mmenke43758e62015-05-04 21:09:464839 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514840 net_log_.GetEntries(&entries);
4841
[email protected]1826a402014-01-08 15:40:484842 size_t log_position = 0;
4843
4844 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4845 entries, log_position);
4846
[email protected]abe1c4a2013-10-25 19:28:514847 // The delegate info should only have been logged on header complete. Other
4848 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:484849 log_position =
4850 ExpectLogContainsSomewhereAfter(entries,
4851 log_position + 1,
4852 NetLog::TYPE_URL_REQUEST_DELEGATE,
4853 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:514854
4855 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4856 log_position + 1);
4857
4858 ASSERT_LT(log_position, entries.size());
4859 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4860 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4861
4862 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4863 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4864 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4865 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4866}
4867
4868// Tests handling of delegate info from a URLRequest::Delegate in the case of
4869// an HTTP redirect.
4870TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4871 ASSERT_TRUE(test_server_.Start());
4872
4873 AsyncLoggingUrlRequestDelegate request_delegate(
4874 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4875 TestURLRequestContext context(true);
4876 context.set_network_delegate(NULL);
4877 context.set_net_log(&net_log_);
4878 context.Init();
4879
4880 {
[email protected]f7022f32014-08-21 16:32:194881 scoped_ptr<URLRequest> r(context.CreateRequest(
4882 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364883 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194884 LoadStateWithParam load_state = r->GetLoadState();
4885 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514886 base::RunLoop().Run();
4887
[email protected]f7022f32014-08-21 16:32:194888 EXPECT_EQ(200, r->GetResponseCode());
4889 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514890 }
4891
mmenke43758e62015-05-04 21:09:464892 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514893 net_log_.GetEntries(&entries);
4894
4895 // Delegate info should only have been logged in OnReceivedRedirect and
4896 // OnResponseStarted.
4897 size_t log_position = 0;
4898 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484899 if (i == 0) {
4900 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4901 entries, log_position) + 1;
4902 }
4903
[email protected]abe1c4a2013-10-25 19:28:514904 log_position = ExpectLogContainsSomewhereAfter(
4905 entries,
4906 log_position,
4907 NetLog::TYPE_URL_REQUEST_DELEGATE,
4908 NetLog::PHASE_BEGIN);
4909
4910 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4911 log_position + 1);
4912
4913 ASSERT_LT(log_position, entries.size());
4914 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4915 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4916 }
4917
4918 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4919 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4920 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4921 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4922}
4923
4924// Tests handling of delegate info from a URLRequest::Delegate in the case of
4925// an HTTP redirect, with cancellation at various points.
4926TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4927 ASSERT_TRUE(test_server_.Start());
4928
4929 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4930 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4931 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4932 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4933 };
4934
4935 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4936 ++test_case) {
4937 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4938 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:514939 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:514940 context.set_network_delegate(NULL);
4941 context.set_net_log(&net_log);
4942 context.Init();
4943
4944 {
[email protected]f7022f32014-08-21 16:32:194945 scoped_ptr<URLRequest> r(context.CreateRequest(
4946 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364947 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194948 LoadStateWithParam load_state = r->GetLoadState();
4949 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514950 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194951 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514952 }
4953
mmenke43758e62015-05-04 21:09:464954 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514955 net_log.GetEntries(&entries);
4956
4957 // Delegate info is always logged in both OnReceivedRedirect and
4958 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4959 // OnResponseStarted delegate call is after cancellation, but logging is
4960 // still currently supported in that call.
4961 size_t log_position = 0;
4962 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484963 if (i == 0) {
4964 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4965 entries, log_position) + 1;
4966 }
4967
[email protected]abe1c4a2013-10-25 19:28:514968 log_position = ExpectLogContainsSomewhereAfter(
4969 entries,
4970 log_position,
4971 NetLog::TYPE_URL_REQUEST_DELEGATE,
4972 NetLog::PHASE_BEGIN);
4973
4974 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4975 log_position + 1);
4976
4977 ASSERT_LT(log_position, entries.size());
4978 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4979 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4980 }
4981
4982 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4983 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4984 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4985 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4986 }
4987}
4988
[email protected]847c0fa92012-11-06 16:37:424989namespace {
4990
4991const char kExtraHeader[] = "Allow-Snafu";
4992const char kExtraValue[] = "fubar";
4993
4994class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204995 void OnReceivedRedirect(URLRequest* request,
4996 const RedirectInfo& redirect_info,
4997 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594998 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:424999 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5000 }
5001};
5002
5003} // namespace
5004
5005TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
5006 ASSERT_TRUE(test_server_.Start());
5007
5008 GURL destination_url = test_server_.GetURL(
5009 "echoheader?" + std::string(kExtraHeader));
5010 GURL original_url = test_server_.GetURL(
5011 "server-redirect?" + destination_url.spec());
5012 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:365013 scoped_ptr<URLRequest> req(
5014 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195015 req->Start();
[email protected]255620da2013-08-19 13:14:295016 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425017
5018 std::string value;
[email protected]f7022f32014-08-21 16:32:195019 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425020 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5021 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195022 EXPECT_FALSE(req->is_pending());
5023 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425024 EXPECT_EQ(kExtraValue, d.data_received());
5025}
5026
[email protected]251a1b92012-11-13 11:01:095027namespace {
5028
5029const char kExtraHeaderToRemove[] = "To-Be-Removed";
5030
5031class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205032 void OnReceivedRedirect(URLRequest* request,
5033 const RedirectInfo& redirect_info,
5034 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595035 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095036 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5037 }
5038};
5039
5040} // namespace
5041
5042TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
5043 ASSERT_TRUE(test_server_.Start());
5044
5045 GURL destination_url = test_server_.GetURL(
5046 "echoheader?" + std::string(kExtraHeaderToRemove));
5047 GURL original_url = test_server_.GetURL(
5048 "server-redirect?" + destination_url.spec());
5049 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:365050 scoped_ptr<URLRequest> req(
5051 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195052 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5053 req->Start();
[email protected]255620da2013-08-19 13:14:295054 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095055
5056 std::string value;
[email protected]f7022f32014-08-21 16:32:195057 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095058 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195059 EXPECT_FALSE(req->is_pending());
5060 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095061 EXPECT_EQ("None", d.data_received());
5062}
5063
[email protected]316c1e5e2012-09-12 15:17:445064TEST_F(URLRequestTestHTTP, CancelTest) {
5065 TestDelegate d;
5066 {
[email protected]f7022f32014-08-21 16:32:195067 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365068 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445069
[email protected]f7022f32014-08-21 16:32:195070 r->Start();
5071 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445072
[email protected]f7022f32014-08-21 16:32:195073 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445074
[email protected]255620da2013-08-19 13:14:295075 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445076
5077 // We expect to receive OnResponseStarted even though the request has been
5078 // cancelled.
5079 EXPECT_EQ(1, d.response_started_count());
5080 EXPECT_EQ(0, d.bytes_received());
5081 EXPECT_FALSE(d.received_data_before_response());
5082 }
5083}
5084
5085TEST_F(URLRequestTestHTTP, CancelTest2) {
5086 ASSERT_TRUE(test_server_.Start());
5087
5088 TestDelegate d;
5089 {
[email protected]f7022f32014-08-21 16:32:195090 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365091 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445092
5093 d.set_cancel_in_response_started(true);
5094
[email protected]f7022f32014-08-21 16:32:195095 r->Start();
5096 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445097
[email protected]255620da2013-08-19 13:14:295098 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445099
5100 EXPECT_EQ(1, d.response_started_count());
5101 EXPECT_EQ(0, d.bytes_received());
5102 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195103 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445104 }
5105}
5106
5107TEST_F(URLRequestTestHTTP, CancelTest3) {
5108 ASSERT_TRUE(test_server_.Start());
5109
5110 TestDelegate d;
5111 {
[email protected]f7022f32014-08-21 16:32:195112 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365113 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445114
5115 d.set_cancel_in_received_data(true);
5116
[email protected]f7022f32014-08-21 16:32:195117 r->Start();
5118 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445119
[email protected]255620da2013-08-19 13:14:295120 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445121
5122 EXPECT_EQ(1, d.response_started_count());
5123 // There is no guarantee about how much data was received
5124 // before the cancel was issued. It could have been 0 bytes,
5125 // or it could have been all the bytes.
5126 // EXPECT_EQ(0, d.bytes_received());
5127 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195128 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445129 }
5130}
5131
5132TEST_F(URLRequestTestHTTP, CancelTest4) {
5133 ASSERT_TRUE(test_server_.Start());
5134
5135 TestDelegate d;
5136 {
[email protected]f7022f32014-08-21 16:32:195137 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365138 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445139
[email protected]f7022f32014-08-21 16:32:195140 r->Start();
5141 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445142
5143 // The request will be implicitly canceled when it is destroyed. The
5144 // test delegate must not post a quit message when this happens because
5145 // this test doesn't actually have a message loop. The quit message would
5146 // get put on this thread's message queue and the next test would exit
5147 // early, causing problems.
5148 d.set_quit_on_complete(false);
5149 }
5150 // expect things to just cleanup properly.
5151
5152 // we won't actually get a received reponse here because we've never run the
5153 // message loop
5154 EXPECT_FALSE(d.received_data_before_response());
5155 EXPECT_EQ(0, d.bytes_received());
5156}
5157
5158TEST_F(URLRequestTestHTTP, CancelTest5) {
5159 ASSERT_TRUE(test_server_.Start());
5160
5161 // populate cache
5162 {
5163 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195164 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365165 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195166 r->Start();
[email protected]255620da2013-08-19 13:14:295167 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195168 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445169 }
5170
5171 // cancel read from cache (see bug 990242)
5172 {
5173 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195174 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365175 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195176 r->Start();
5177 r->Cancel();
[email protected]255620da2013-08-19 13:14:295178 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445179
[email protected]f7022f32014-08-21 16:32:195180 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445181 EXPECT_EQ(1, d.response_started_count());
5182 EXPECT_EQ(0, d.bytes_received());
5183 EXPECT_FALSE(d.received_data_before_response());
5184 }
5185}
5186
5187TEST_F(URLRequestTestHTTP, PostTest) {
5188 ASSERT_TRUE(test_server_.Start());
5189 HTTPUploadDataOperationTest("POST");
5190}
5191
5192TEST_F(URLRequestTestHTTP, PutTest) {
5193 ASSERT_TRUE(test_server_.Start());
5194 HTTPUploadDataOperationTest("PUT");
5195}
5196
5197TEST_F(URLRequestTestHTTP, PostEmptyTest) {
5198 ASSERT_TRUE(test_server_.Start());
5199
5200 TestDelegate d;
5201 {
[email protected]f7022f32014-08-21 16:32:195202 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365203 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195204 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445205
[email protected]f7022f32014-08-21 16:32:195206 r->Start();
5207 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445208
[email protected]255620da2013-08-19 13:14:295209 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445210
[email protected]329b68b2012-11-14 17:54:275211 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195212 << "request failed: " << r->status().status()
5213 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445214
5215 EXPECT_FALSE(d.received_data_before_response());
5216 EXPECT_TRUE(d.data_received().empty());
5217 }
5218}
5219
5220TEST_F(URLRequestTestHTTP, PostFileTest) {
5221 ASSERT_TRUE(test_server_.Start());
5222
5223 TestDelegate d;
5224 {
[email protected]f7022f32014-08-21 16:32:195225 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365226 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195227 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445228
[email protected]6cdfd7f2013-02-08 20:40:155229 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445230 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025231 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445232
[email protected]f288ef02012-12-15 20:28:285233 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445234
[email protected]6cdfd7f2013-02-08 20:40:155235 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445236 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475237 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445238 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:365239 element_readers.push_back(
skyostil4891b25b2015-06-11 11:43:455240 new UploadFileElementReader(base::ThreadTaskRunnerHandle::Get().get(),
5241 path, 0, kuint64max, base::Time()));
mmenkecbc2b712014-10-09 20:29:075242 r->set_upload(make_scoped_ptr<UploadDataStream>(
5243 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:445244
[email protected]f7022f32014-08-21 16:32:195245 r->Start();
5246 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445247
[email protected]255620da2013-08-19 13:14:295248 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445249
pkasting6b68a162014-12-01 22:10:295250 int64 size64 = 0;
5251 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5252 ASSERT_LE(size64, std::numeric_limits<int>::max());
5253 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175254 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445255
[email protected]7600d0b2013-12-08 21:43:305256 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445257
[email protected]329b68b2012-11-14 17:54:275258 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195259 << "request failed: " << r->status().status()
5260 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445261
5262 EXPECT_FALSE(d.received_data_before_response());
5263
[email protected]329b68b2012-11-14 17:54:275264 EXPECT_EQ(size, d.bytes_received());
5265 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445266 }
5267}
5268
[email protected]999dd8c2013-11-12 06:45:545269TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
5270 ASSERT_TRUE(test_server_.Start());
5271
5272 TestDelegate d;
5273 {
[email protected]f7022f32014-08-21 16:32:195274 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365275 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195276 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545277
5278 ScopedVector<UploadElementReader> element_readers;
5279
5280 element_readers.push_back(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455281 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545282 base::FilePath(FILE_PATH_LITERAL(
5283 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
skyostil4891b25b2015-06-11 11:43:455284 0, kuint64max, base::Time()));
mmenkecbc2b712014-10-09 20:29:075285 r->set_upload(make_scoped_ptr<UploadDataStream>(
5286 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]999dd8c2013-11-12 06:45:545287
[email protected]f7022f32014-08-21 16:32:195288 r->Start();
5289 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545290
5291 base::RunLoop().Run();
5292
[email protected]999dd8c2013-11-12 06:45:545293 EXPECT_TRUE(d.request_failed());
5294 EXPECT_FALSE(d.received_data_before_response());
5295 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195296 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5297 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545298 }
5299}
5300
[email protected]316c1e5e2012-09-12 15:17:445301TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5302 ASSERT_TRUE(test_server_.Start());
5303
5304 TestDelegate d;
5305 {
[email protected]f7022f32014-08-21 16:32:195306 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365307 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195308 r->EnableChunkedUpload();
5309 r->set_method("POST");
5310 AddChunksToUpload(r.get());
5311 r->Start();
5312 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445313
[email protected]255620da2013-08-19 13:14:295314 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445315
[email protected]f7022f32014-08-21 16:32:195316 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445317 }
5318}
5319
[email protected]329b68b2012-11-14 17:54:275320TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5321 ASSERT_TRUE(test_server_.Start());
5322
5323 TestDelegate d;
5324 {
[email protected]f7022f32014-08-21 16:32:195325 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365326 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195327 r->EnableChunkedUpload();
5328 r->set_method("POST");
5329 r->Start();
5330 EXPECT_TRUE(r->is_pending());
5331 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295332 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275333
[email protected]f7022f32014-08-21 16:32:195334 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275335 }
5336}
5337
[email protected]316c1e5e2012-09-12 15:17:445338TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5339 ASSERT_TRUE(test_server_.Start());
5340
5341 TestDelegate d;
5342 {
[email protected]f7022f32014-08-21 16:32:195343 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365344 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195345 r->EnableChunkedUpload();
5346 r->set_method("POST");
5347 r->Start();
5348 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445349
[email protected]255620da2013-08-19 13:14:295350 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195351 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295352 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445353
[email protected]f7022f32014-08-21 16:32:195354 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445355 }
5356}
5357
5358TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5359 ASSERT_TRUE(test_server_.Start());
5360
5361 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195362 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365363 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195364 req->Start();
[email protected]255620da2013-08-19 13:14:295365 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445366
[email protected]f7022f32014-08-21 16:32:195367 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445368
5369 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195370 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445371
5372 std::string header;
5373 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5374 EXPECT_EQ("private", header);
5375
5376 header.clear();
5377 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5378 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5379
5380 // The response has two "X-Multiple-Entries" headers.
5381 // This verfies our output has them concatenated together.
5382 header.clear();
5383 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5384 EXPECT_EQ("a, b", header);
5385}
5386
[email protected]242d8562012-10-30 21:20:465387TEST_F(URLRequestTestHTTP, ProcessSTS) {
estarka5da76702015-04-09 04:00:165388 SpawnedTestServer::SSLOptions ssl_options(
5389 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475390 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5391 ssl_options,
5392 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465393 ASSERT_TRUE(https_test_server.Start());
5394
estarka5da76702015-04-09 04:00:165395 std::string test_server_hostname = https_test_server.GetURL("").host();
5396
[email protected]242d8562012-10-30 21:20:465397 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195398 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365399 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5400 &d));
[email protected]f7022f32014-08-21 16:32:195401 request->Start();
[email protected]255620da2013-08-19 13:14:295402 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465403
5404 TransportSecurityState* security_state =
5405 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405406 TransportSecurityState::STSState sts_state;
5407 TransportSecurityState::PKPState pkp_state;
5408 EXPECT_TRUE(
5409 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5410 EXPECT_FALSE(
5411 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5412 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5413 sts_state.upgrade_mode);
5414 EXPECT_TRUE(sts_state.include_subdomains);
5415 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275416#if defined(OS_ANDROID)
5417 // Android's CertVerifyProc does not (yet) handle pins.
5418#else
martijnc0d6b622015-06-30 19:14:405419 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
[email protected]37fd55fb2013-06-29 13:13:275420#endif
5421}
5422
estarka5da76702015-04-09 04:00:165423TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
mmenke9f2ec60c2015-06-01 20:59:475424 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5425 SpawnedTestServer::SSLOptions(),
5426 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165427 ASSERT_TRUE(https_test_server.Start());
5428 // Make sure this test fails if the test server is changed to not
5429 // listen on an IP by default.
5430 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5431 std::string test_server_hostname = https_test_server.GetURL("").host();
5432
5433 TestDelegate d;
5434 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5435 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5436 &d));
5437 request->Start();
5438 base::RunLoop().Run();
5439
5440 TransportSecurityState* security_state =
5441 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405442 TransportSecurityState::STSState sts_state;
5443 EXPECT_FALSE(
5444 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165445}
5446
[email protected]37fd55fb2013-06-29 13:13:275447// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5448// reject HPKP headers, and a test setting only HPKP headers will fail (no
martijnc0d6b622015-06-30 19:14:405449// PKPState present because header rejected).
[email protected]37fd55fb2013-06-29 13:13:275450#if defined(OS_ANDROID)
5451#define MAYBE_ProcessPKP DISABLED_ProcessPKP
estark06e0dac2015-08-07 21:56:015452#define MAYBE_ProcessPKPAndSendReport DISABLED_ProcessPKPAndSendReport
5453#define MAYBE_ProcessPKPReportOnly DISABLED_ProcessPKPReportOnly
5454#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5455 DISABLED_ProcessPKPReportOnlyWithNoViolation
[email protected]37fd55fb2013-06-29 13:13:275456#else
5457#define MAYBE_ProcessPKP ProcessPKP
estark06e0dac2015-08-07 21:56:015458#define MAYBE_ProcessPKPAndSendReport ProcessPKPAndSendReport
5459#define MAYBE_ProcessPKPReportOnly ProcessPKPReportOnly
5460#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5461 ProcessPKPReportOnlyWithNoViolation
[email protected]37fd55fb2013-06-29 13:13:275462#endif
5463
estark06e0dac2015-08-07 21:56:015464namespace {
5465const char kHPKPReportUri[] = "https://hpkp-report.test";
5466} // namespace
5467
[email protected]37fd55fb2013-06-29 13:13:275468// Tests that enabling HPKP on a domain does not affect the HSTS
5469// validity/expiration.
5470TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estark06e0dac2015-08-07 21:56:015471 GURL report_uri(kHPKPReportUri);
estarka5da76702015-04-09 04:00:165472 SpawnedTestServer::SSLOptions ssl_options(
5473 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475474 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5475 ssl_options,
5476 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275477 ASSERT_TRUE(https_test_server.Start());
5478
estarka5da76702015-04-09 04:00:165479 std::string test_server_hostname = https_test_server.GetURL("").host();
5480
[email protected]37fd55fb2013-06-29 13:13:275481 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195482 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365483 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5484 &d));
[email protected]f7022f32014-08-21 16:32:195485 request->Start();
[email protected]255620da2013-08-19 13:14:295486 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275487
5488 TransportSecurityState* security_state =
5489 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405490 TransportSecurityState::STSState sts_state;
5491 TransportSecurityState::PKPState pkp_state;
5492 EXPECT_FALSE(
5493 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5494 EXPECT_TRUE(
5495 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5496 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
5497 sts_state.upgrade_mode);
5498 EXPECT_FALSE(sts_state.include_subdomains);
5499 EXPECT_FALSE(pkp_state.include_subdomains);
5500 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:015501 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:405502 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:465503}
5504
estark06e0dac2015-08-07 21:56:015505// Tests that reports get sent on HPKP violations when a report-uri is set.
5506TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPAndSendReport) {
5507 GURL report_uri(kHPKPReportUri);
5508 SpawnedTestServer::SSLOptions ssl_options(
5509 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
5510 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5511 ssl_options,
5512 base::FilePath(kTestFilePath));
5513
5514 ASSERT_TRUE(https_test_server.Start());
5515
5516 std::string test_server_hostname = https_test_server.GetURL("").host();
5517
5518 // Set up a pin for |test_server_hostname|.
5519 TransportSecurityState security_state;
5520 const base::Time current_time(base::Time::Now());
5521 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
5522 HashValueVector hashes;
5523 HashValue hash1;
5524 HashValue hash2;
5525 // The values here don't matter, as long as they are different from
5526 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:445527 ASSERT_TRUE(
5528 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
5529 ASSERT_TRUE(
5530 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:015531 hashes.push_back(hash1);
5532 hashes.push_back(hash2);
5533 security_state.AddHPKP(test_server_hostname, expiry,
5534 false, /* include subdomains */
5535 hashes, report_uri);
5536
5537 MockCertificateReportSender mock_report_sender;
5538 security_state.SetReportSender(&mock_report_sender);
5539
5540 // Set up a MockCertVerifier to trigger a violation of the previously
5541 // set pin.
5542 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5543 ASSERT_TRUE(cert);
5544
5545 MockCertVerifier cert_verifier;
5546 CertVerifyResult verify_result;
5547 verify_result.verified_cert = cert;
5548 verify_result.is_issued_by_known_root = true;
5549 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:445550 ASSERT_TRUE(
5551 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:015552 verify_result.public_key_hashes.push_back(hash3);
5553 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5554
5555 TestNetworkDelegate network_delegate;
5556 TestURLRequestContext context(true);
5557 context.set_transport_security_state(&security_state);
5558 context.set_network_delegate(&network_delegate);
5559 context.set_cert_verifier(&cert_verifier);
5560 context.Init();
5561
5562 // Now send a request to trigger the violation.
5563 TestDelegate d;
5564 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
5565 https_test_server.GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
5566 violating_request->Start();
5567 base::RunLoop().Run();
5568
5569 // Check that a report was sent.
5570 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5571 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5572 scoped_ptr<base::Value> value(
5573 base::JSONReader::Read(mock_report_sender.latest_report()));
5574 ASSERT_TRUE(value);
5575 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
5576 base::DictionaryValue* report_dict;
5577 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
5578 std::string report_hostname;
5579 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
5580 EXPECT_EQ(test_server_hostname, report_hostname);
5581}
5582
5583// Tests that reports get sent on requests with
5584// Public-Key-Pins-Report-Only headers.
5585TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnly) {
5586 GURL report_uri(kHPKPReportUri);
5587 SpawnedTestServer::SSLOptions ssl_options(
5588 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
5589 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5590 ssl_options,
5591 base::FilePath(kTestFilePath));
5592
5593 ASSERT_TRUE(https_test_server.Start());
5594
5595 std::string test_server_hostname = https_test_server.GetURL("").host();
5596
5597 TransportSecurityState security_state;
5598 MockCertificateReportSender mock_report_sender;
5599 security_state.SetReportSender(&mock_report_sender);
5600
5601 // Set up a MockCertVerifier to violate the pin in the Report-Only
5602 // header.
5603 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5604 ASSERT_TRUE(cert);
5605
5606 MockCertVerifier cert_verifier;
5607 CertVerifyResult verify_result;
5608 verify_result.verified_cert = cert;
5609 verify_result.is_issued_by_known_root = true;
5610 HashValue hash;
5611 // This value doesn't matter, as long as it is different from the pins
5612 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:445613 ASSERT_TRUE(
5614 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:015615 verify_result.public_key_hashes.push_back(hash);
5616 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5617
5618 TestNetworkDelegate network_delegate;
5619 TestURLRequestContext context(true);
5620 context.set_transport_security_state(&security_state);
5621 context.set_network_delegate(&network_delegate);
5622 context.set_cert_verifier(&cert_verifier);
5623 context.Init();
5624
5625 // Now send a request to trigger the violation.
5626 TestDelegate d;
5627 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
5628 https_test_server.GetURL("files/hpkp-headers-report-only.html"),
5629 DEFAULT_PRIORITY, &d));
5630 violating_request->Start();
5631 base::RunLoop().Run();
5632
5633 // Check that a report was sent.
5634 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5635 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5636 scoped_ptr<base::Value> value(
5637 base::JSONReader::Read(mock_report_sender.latest_report()));
5638 ASSERT_TRUE(value);
5639 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
5640 base::DictionaryValue* report_dict;
5641 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
5642 std::string report_hostname;
5643 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
5644 EXPECT_EQ(test_server_hostname, report_hostname);
5645}
5646
5647// Tests that reports do not get sent on requests with
5648// Public-Key-Pins-Report-Only headers that don't have pin violations.
5649TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnlyWithNoViolation) {
5650 GURL report_uri(kHPKPReportUri);
5651 SpawnedTestServer::SSLOptions ssl_options(
5652 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
5653 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5654 ssl_options,
5655 base::FilePath(kTestFilePath));
5656
5657 ASSERT_TRUE(https_test_server.Start());
5658
5659 std::string test_server_hostname = https_test_server.GetURL("").host();
5660
5661 TransportSecurityState security_state;
5662 MockCertificateReportSender mock_report_sender;
5663 security_state.SetReportSender(&mock_report_sender);
5664
5665 TestNetworkDelegate network_delegate;
5666 MockCertVerifier mock_cert_verifier;
5667 TestURLRequestContext context(true);
5668 context.set_transport_security_state(&security_state);
5669 context.set_network_delegate(&network_delegate);
5670 context.set_cert_verifier(&mock_cert_verifier);
5671 mock_cert_verifier.set_default_result(OK);
5672 context.Init();
5673
5674 // Now send a request that does not trigger the violation.
5675 TestDelegate d;
5676 scoped_ptr<URLRequest> request(context.CreateRequest(
5677 https_test_server.GetURL("files/hpkp-headers-report-only.html"),
5678 DEFAULT_PRIORITY, &d));
5679 request->Start();
5680 base::RunLoop().Run();
5681
5682 // Check that a report was not sent.
5683 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
5684 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
5685}
5686
estarka5da76702015-04-09 04:00:165687TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
mmenke9f2ec60c2015-06-01 20:59:475688 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5689 SpawnedTestServer::SSLOptions(),
5690 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165691 ASSERT_TRUE(https_test_server.Start());
5692 // Make sure this test fails if the test server is changed to not
5693 // listen on an IP by default.
5694 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5695 std::string test_server_hostname = https_test_server.GetURL("").host();
5696
5697 TestDelegate d;
5698 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5699 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5700 &d));
5701 request->Start();
5702 base::RunLoop().Run();
5703
5704 TransportSecurityState* security_state =
5705 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405706 TransportSecurityState::PKPState pkp_state;
5707 EXPECT_FALSE(
5708 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:165709}
5710
[email protected]242d8562012-10-30 21:20:465711TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
estarka5da76702015-04-09 04:00:165712 SpawnedTestServer::SSLOptions ssl_options(
5713 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475714 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5715 ssl_options,
5716 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465717 ASSERT_TRUE(https_test_server.Start());
5718
estarka5da76702015-04-09 04:00:165719 std::string test_server_hostname = https_test_server.GetURL("").host();
5720
[email protected]242d8562012-10-30 21:20:465721 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195722 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]242d8562012-10-30 21:20:465723 https_test_server.GetURL("files/hsts-multiple-headers.html"),
davidben151423e2015-03-23 18:48:365724 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195725 request->Start();
[email protected]255620da2013-08-19 13:14:295726 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465727
5728 // We should have set parameters from the first header, not the second.
5729 TransportSecurityState* security_state =
5730 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405731 TransportSecurityState::STSState sts_state;
5732 EXPECT_TRUE(
5733 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5734 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5735 sts_state.upgrade_mode);
5736 EXPECT_FALSE(sts_state.include_subdomains);
5737 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:465738}
5739
[email protected]9f972ec2013-04-10 20:24:365740TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
estarka5da76702015-04-09 04:00:165741 SpawnedTestServer::SSLOptions ssl_options(
5742 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475743 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5744 ssl_options,
5745 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:365746 ASSERT_TRUE(https_test_server.Start());
5747
estarka5da76702015-04-09 04:00:165748 std::string test_server_hostname = https_test_server.GetURL("").host();
5749
[email protected]9f972ec2013-04-10 20:24:365750 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195751 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]9f972ec2013-04-10 20:24:365752 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
davidben151423e2015-03-23 18:48:365753 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195754 request->Start();
[email protected]255620da2013-08-19 13:14:295755 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365756
5757 // We should have set parameters from the first header, not the second.
5758 TransportSecurityState* security_state =
5759 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405760 TransportSecurityState::STSState sts_state;
5761 TransportSecurityState::PKPState pkp_state;
5762 EXPECT_TRUE(
5763 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5764 EXPECT_TRUE(
5765 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5766 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5767 sts_state.upgrade_mode);
[email protected]9f972ec2013-04-10 20:24:365768#if defined(OS_ANDROID)
5769 // Android's CertVerifyProc does not (yet) handle pins.
5770#else
martijnc0d6b622015-06-30 19:14:405771 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
[email protected]9f972ec2013-04-10 20:24:365772#endif
martijnc0d6b622015-06-30 19:14:405773 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:365774
[email protected]a165f092013-06-12 16:10:055775 // Even though there is an HSTS header asserting includeSubdomains, it is
5776 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:405777 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:055778 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:405779 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365780}
5781
[email protected]37fd55fb2013-06-29 13:13:275782// Tests that when multiple HPKP headers are present, asserting different
5783// policies, that only the first such policy is processed.
5784TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
estarka5da76702015-04-09 04:00:165785 SpawnedTestServer::SSLOptions ssl_options(
5786 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475787 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5788 ssl_options,
5789 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275790 ASSERT_TRUE(https_test_server.Start());
5791
estarka5da76702015-04-09 04:00:165792 std::string test_server_hostname = https_test_server.GetURL("").host();
5793
[email protected]37fd55fb2013-06-29 13:13:275794 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195795 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]37fd55fb2013-06-29 13:13:275796 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:365797 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195798 request->Start();
[email protected]255620da2013-08-19 13:14:295799 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275800
5801 TransportSecurityState* security_state =
5802 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405803 TransportSecurityState::STSState sts_state;
5804 TransportSecurityState::PKPState pkp_state;
5805 EXPECT_TRUE(
5806 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5807 EXPECT_TRUE(
5808 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5809 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5810 sts_state.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:275811#if defined(OS_ANDROID)
5812 // Android's CertVerifyProc does not (yet) handle pins.
5813#else
martijnc0d6b622015-06-30 19:14:405814 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
[email protected]37fd55fb2013-06-29 13:13:275815#endif
martijnc0d6b622015-06-30 19:14:405816 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:275817
martijnc0d6b622015-06-30 19:14:405818 EXPECT_TRUE(sts_state.include_subdomains);
5819 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275820}
5821
[email protected]316c1e5e2012-09-12 15:17:445822TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5823 ASSERT_TRUE(test_server_.Start());
5824
5825 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195826 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5827 test_server_.GetURL("files/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:365828 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195829 req->Start();
[email protected]255620da2013-08-19 13:14:295830 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445831
5832 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:195833 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:445834 EXPECT_EQ("text/html", mime_type);
5835
5836 std::string charset;
[email protected]f7022f32014-08-21 16:32:195837 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:445838 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:195839 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445840}
5841
[email protected]02494ec2014-05-07 15:05:295842TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:345843 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:345844 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:345845 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025846 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345847
5848 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505849 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345850}
5851
[email protected]02494ec2014-05-07 15:05:295852#if !defined(DISABLE_FILE_SUPPORT)
5853TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5854 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5855 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:455856 FileProtocolHandler file_protocol_handler(
5857 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:295858 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5859
5860 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505861 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:295862}
5863
[email protected]588614c22013-08-16 00:09:025864TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445865 ASSERT_TRUE(test_server_.Start());
5866
5867 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195868 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365869 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY,
5870 &d));
[email protected]f7022f32014-08-21 16:32:195871 req->Start();
[email protected]255620da2013-08-19 13:14:295872 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445873
[email protected]f7022f32014-08-21 16:32:195874 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5875 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445876}
[email protected]02494ec2014-05-07 15:05:295877#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:445878
[email protected]588614c22013-08-16 00:09:025879TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5880 ASSERT_TRUE(test_server_.Start());
5881
5882 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195883 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365884 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY,
5885 &d));
[email protected]f7022f32014-08-21 16:32:195886 req->Start();
[email protected]588614c22013-08-16 00:09:025887 base::MessageLoop::current()->Run();
5888
[email protected]f7022f32014-08-21 16:32:195889 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5890 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:025891}
5892
[email protected]316c1e5e2012-09-12 15:17:445893TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5894 ASSERT_TRUE(test_server_.Start());
5895
5896 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195897 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5898 test_server_.GetURL("files/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:365899 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195900 req->Start();
[email protected]255620da2013-08-19 13:14:295901 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445902
[email protected]f7022f32014-08-21 16:32:195903 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5904 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445905}
5906
[email protected]e50efea2014-03-24 18:41:005907// Make sure redirects are cached, despite not reading their bodies.
5908TEST_F(URLRequestTestHTTP, CacheRedirect) {
5909 ASSERT_TRUE(test_server_.Start());
5910 GURL redirect_url =
5911 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5912
5913 {
5914 TestDelegate d;
davidben151423e2015-03-23 18:48:365915 scoped_ptr<URLRequest> req(
5916 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195917 req->Start();
[email protected]e50efea2014-03-24 18:41:005918 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195919 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005920 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195921 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005922 }
5923
5924 {
5925 TestDelegate d;
5926 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:365927 scoped_ptr<URLRequest> req(
5928 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195929 req->Start();
[email protected]e50efea2014-03-24 18:41:005930 base::RunLoop().Run();
5931
5932 EXPECT_EQ(1, d.received_redirect_count());
5933 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195934 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005935
[email protected]f7022f32014-08-21 16:32:195936 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:005937 base::RunLoop().Run();
5938 EXPECT_EQ(1, d.received_redirect_count());
5939 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195940 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5941 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005942 }
5943}
5944
5945// Make sure a request isn't cached when a NetworkDelegate forces a redirect
5946// when the headers are read, since the body won't have been read.
5947TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5948 ASSERT_TRUE(test_server_.Start());
5949 // URL that is normally cached.
5950 GURL initial_url = test_server_.GetURL("cachetime");
5951
5952 {
5953 // Set up the TestNetworkDelegate tp force a redirect.
5954 GURL redirect_to_url = test_server_.GetURL("echo");
5955 default_network_delegate_.set_redirect_on_headers_received_url(
5956 redirect_to_url);
5957
5958 TestDelegate d;
davidben151423e2015-03-23 18:48:365959 scoped_ptr<URLRequest> req(
5960 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195961 req->Start();
[email protected]e50efea2014-03-24 18:41:005962 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195963 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005964 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195965 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:005966 }
5967
5968 {
5969 TestDelegate d;
davidben151423e2015-03-23 18:48:365970 scoped_ptr<URLRequest> req(
5971 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195972 req->Start();
[email protected]e50efea2014-03-24 18:41:005973 base::RunLoop().Run();
5974
[email protected]f7022f32014-08-21 16:32:195975 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5976 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005977 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195978 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:005979 }
5980}
5981
[email protected]5f714132014-03-26 10:41:165982// Tests that redirection to an unsafe URL is allowed when it has been marked as
5983// safe.
5984TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5985 ASSERT_TRUE(test_server_.Start());
5986
5987 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5988 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5989 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5990
5991 TestDelegate d;
5992 {
[email protected]f7022f32014-08-21 16:32:195993 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365994 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165995
[email protected]f7022f32014-08-21 16:32:195996 r->Start();
[email protected]5f714132014-03-26 10:41:165997 base::RunLoop().Run();
5998
[email protected]f7022f32014-08-21 16:32:195999 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:166000
[email protected]f7022f32014-08-21 16:32:196001 EXPECT_EQ(2U, r->url_chain().size());
6002 EXPECT_EQ(OK, r->status().error());
6003 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166004 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6005 }
6006}
6007
6008// Tests that a redirect to a different unsafe URL is blocked, even after adding
6009// some other URL to the whitelist.
6010TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
6011 ASSERT_TRUE(test_server_.Start());
6012
6013 GURL unsafe_url("data:text/html,something");
6014 GURL different_unsafe_url("data:text/html,something-else");
6015 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6016 default_network_delegate_.set_allowed_unsafe_redirect_url(
6017 different_unsafe_url);
6018
6019 TestDelegate d;
6020 {
[email protected]f7022f32014-08-21 16:32:196021 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366022 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166023
[email protected]f7022f32014-08-21 16:32:196024 r->Start();
[email protected]5f714132014-03-26 10:41:166025 base::RunLoop().Run();
6026
[email protected]f7022f32014-08-21 16:32:196027 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
6028 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:166029 }
6030}
6031
[email protected]5f714132014-03-26 10:41:166032// Redirects from an URL with fragment to an unsafe URL with fragment should
6033// be allowed, and the reference fragment of the target URL should be preserved.
6034TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
6035 ASSERT_TRUE(test_server_.Start());
6036
6037 GURL original_url(test_server_.GetURL("original#fragment1"));
6038 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6039 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6040
6041 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6042 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6043
6044 TestDelegate d;
6045 {
davidben151423e2015-03-23 18:48:366046 scoped_ptr<URLRequest> r(
6047 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166048
[email protected]f7022f32014-08-21 16:32:196049 r->Start();
[email protected]5f714132014-03-26 10:41:166050 base::RunLoop().Run();
6051
[email protected]f7022f32014-08-21 16:32:196052 EXPECT_EQ(2U, r->url_chain().size());
6053 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6054 EXPECT_EQ(OK, r->status().error());
6055 EXPECT_EQ(original_url, r->original_url());
6056 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166057 }
6058}
6059
6060// When a delegate has specified a safe redirect URL, but it does not match the
6061// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146062TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:166063 ASSERT_TRUE(test_server_.Start());
6064
6065 GURL original_url(test_server_.GetURL("original#expected-fragment"));
6066 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
6067 GURL redirect_url(test_server_.GetURL("target"));
6068 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
6069
6070 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6071 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6072
6073 TestDelegate d;
6074 {
davidben151423e2015-03-23 18:48:366075 scoped_ptr<URLRequest> r(
6076 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166077
[email protected]f7022f32014-08-21 16:32:196078 r->Start();
[email protected]5f714132014-03-26 10:41:166079 base::RunLoop().Run();
6080
[email protected]f7022f32014-08-21 16:32:196081 EXPECT_EQ(2U, r->url_chain().size());
6082 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6083 EXPECT_EQ(OK, r->status().error());
6084 EXPECT_EQ(original_url, r->original_url());
6085 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166086 }
6087}
6088
[email protected]f878230e2014-04-03 15:36:146089// When a delegate has specified a safe redirect URL, assume that the redirect
6090// URL should not be changed. In particular, the reference fragment should not
6091// be modified.
6092TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
6093 ASSERT_TRUE(test_server_.Start());
6094
6095 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
6096 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6097
6098 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6099 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6100
6101 TestDelegate d;
6102 {
davidben151423e2015-03-23 18:48:366103 scoped_ptr<URLRequest> r(
6104 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146105
[email protected]f7022f32014-08-21 16:32:196106 r->Start();
[email protected]f878230e2014-04-03 15:36:146107 base::RunLoop().Run();
6108
[email protected]f7022f32014-08-21 16:32:196109 EXPECT_EQ(2U, r->url_chain().size());
6110 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6111 EXPECT_EQ(OK, r->status().error());
6112 EXPECT_EQ(original_url, r->original_url());
6113 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146114 }
6115}
6116
6117// When a URLRequestRedirectJob is created, the redirection must be followed and
6118// the reference fragment of the target URL must not be modified.
6119TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
6120 ASSERT_TRUE(test_server_.Start());
6121
6122 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
6123 GURL redirect_url(test_server_.GetURL("echo"));
6124
6125 TestDelegate d;
davidben151423e2015-03-23 18:48:366126 scoped_ptr<URLRequest> r(
6127 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146128
6129 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196130 r.get(), &default_network_delegate_, redirect_url,
[email protected]f878230e2014-04-03 15:36:146131 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6132 AddTestInterceptor()->set_main_intercept_job(job);
6133
[email protected]f7022f32014-08-21 16:32:196134 r->Start();
[email protected]f878230e2014-04-03 15:36:146135 base::RunLoop().Run();
6136
[email protected]f7022f32014-08-21 16:32:196137 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6138 EXPECT_EQ(OK, r->status().error());
6139 EXPECT_EQ(original_url, r->original_url());
6140 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146141}
6142
[email protected]316c1e5e2012-09-12 15:17:446143TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
6144 ASSERT_TRUE(test_server_.Start());
6145
6146 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196147 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366148 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196149 req->SetReferrer("http://user:[email protected]/");
6150 req->Start();
[email protected]255620da2013-08-19 13:14:296151 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446152
6153 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6154}
6155
[email protected]99ecf6e2013-04-10 22:46:136156TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
6157 ASSERT_TRUE(test_server_.Start());
6158
6159 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196160 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366161 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196162 req->SetReferrer("http://foo.com/test#fragment");
6163 req->Start();
[email protected]255620da2013-08-19 13:14:296164 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136165
6166 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6167}
6168
6169TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
6170 ASSERT_TRUE(test_server_.Start());
6171
6172 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196173 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366174 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196175 req->SetReferrer("http://foo.com/test#fragment");
6176 req->SetReferrer("");
6177 req->Start();
[email protected]255620da2013-08-19 13:14:296178 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136179
6180 EXPECT_EQ(std::string("None"), d.data_received());
6181}
6182
[email protected]1826a402014-01-08 15:40:486183// Defer network start and then resume, checking that the request was a success
6184// and bytes were received.
6185TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
6186 ASSERT_TRUE(test_server_.Start());
6187
6188 TestDelegate d;
6189 {
6190 d.set_quit_on_network_start(true);
6191 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:366192 scoped_ptr<URLRequest> req(
6193 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486194
[email protected]f7022f32014-08-21 16:32:196195 req->Start();
[email protected]1826a402014-01-08 15:40:486196 base::RunLoop().Run();
6197
6198 EXPECT_EQ(1, d.received_before_network_start_count());
6199 EXPECT_EQ(0, d.response_started_count());
6200
[email protected]f7022f32014-08-21 16:32:196201 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486202 base::RunLoop().Run();
6203
6204 EXPECT_EQ(1, d.response_started_count());
6205 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196206 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486207 }
6208}
6209
6210// Check that OnBeforeNetworkStart is only called once even if there is a
6211// redirect.
6212TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
6213 ASSERT_TRUE(test_server_.Start());
6214
6215 TestDelegate d;
6216 {
6217 d.set_quit_on_redirect(true);
6218 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:196219 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366220 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486221
[email protected]f7022f32014-08-21 16:32:196222 req->Start();
[email protected]1826a402014-01-08 15:40:486223 base::RunLoop().Run();
6224
6225 EXPECT_EQ(1, d.received_before_network_start_count());
6226 EXPECT_EQ(0, d.response_started_count());
6227 EXPECT_EQ(0, d.received_redirect_count());
6228
[email protected]f7022f32014-08-21 16:32:196229 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486230 base::RunLoop().Run();
6231
6232 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196233 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:486234 base::RunLoop().Run();
6235
6236 // Check that the redirect's new network transaction does not get propagated
6237 // to a second OnBeforeNetworkStart() notification.
6238 EXPECT_EQ(1, d.received_before_network_start_count());
6239
6240 EXPECT_EQ(1, d.response_started_count());
6241 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196242 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486243 }
6244}
6245
6246// Cancel the request after learning that the request would use the network.
6247TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
6248 ASSERT_TRUE(test_server_.Start());
6249
6250 TestDelegate d;
6251 {
6252 d.set_quit_on_network_start(true);
6253 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:366254 scoped_ptr<URLRequest> req(
6255 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486256
[email protected]f7022f32014-08-21 16:32:196257 req->Start();
[email protected]1826a402014-01-08 15:40:486258 base::RunLoop().Run();
6259
6260 EXPECT_EQ(1, d.received_before_network_start_count());
6261 EXPECT_EQ(0, d.response_started_count());
6262
[email protected]f7022f32014-08-21 16:32:196263 req->Cancel();
[email protected]1826a402014-01-08 15:40:486264 base::RunLoop().Run();
6265
6266 EXPECT_EQ(1, d.response_started_count());
6267 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196268 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:486269 }
6270}
6271
[email protected]316c1e5e2012-09-12 15:17:446272TEST_F(URLRequestTestHTTP, CancelRedirect) {
6273 ASSERT_TRUE(test_server_.Start());
6274
6275 TestDelegate d;
6276 {
6277 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:196278 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366279 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196280 req->Start();
[email protected]255620da2013-08-19 13:14:296281 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446282
6283 EXPECT_EQ(1, d.response_started_count());
6284 EXPECT_EQ(0, d.bytes_received());
6285 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196286 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446287 }
6288}
6289
6290TEST_F(URLRequestTestHTTP, DeferredRedirect) {
6291 ASSERT_TRUE(test_server_.Start());
6292
6293 TestDelegate d;
6294 {
6295 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:046296 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366297 scoped_ptr<URLRequest> req(
6298 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046299
[email protected]f7022f32014-08-21 16:32:196300 req->Start();
[email protected]255620da2013-08-19 13:14:296301 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446302
6303 EXPECT_EQ(1, d.received_redirect_count());
6304
[email protected]f7022f32014-08-21 16:32:196305 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296306 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446307
6308 EXPECT_EQ(1, d.response_started_count());
6309 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196310 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446311
[email protected]6cdfd7f2013-02-08 20:40:156312 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446313 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476314 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446315 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6316
6317 std::string contents;
[email protected]82f84b92013-08-30 18:23:506318 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446319 EXPECT_EQ(contents, d.data_received());
6320 }
6321}
6322
[email protected]79e1fd62013-06-20 06:50:046323TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
6324 ASSERT_TRUE(test_server_.Start());
6325
6326 TestDelegate d;
6327 {
6328 d.set_quit_on_redirect(true);
6329 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366330 scoped_ptr<URLRequest> req(
6331 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046332
6333 EXPECT_FALSE(d.have_full_request_headers());
6334
[email protected]f7022f32014-08-21 16:32:196335 req->Start();
[email protected]255620da2013-08-19 13:14:296336 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046337
6338 EXPECT_EQ(1, d.received_redirect_count());
6339 EXPECT_TRUE(d.have_full_request_headers());
6340 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6341 d.ClearFullRequestHeaders();
6342
[email protected]f7022f32014-08-21 16:32:196343 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296344 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046345
6346 GURL target_url(test_server_.GetURL("files/with-headers.html"));
6347 EXPECT_EQ(1, d.response_started_count());
6348 EXPECT_TRUE(d.have_full_request_headers());
6349 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6350 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196351 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046352
6353 base::FilePath path;
6354 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476355 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046356 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6357
6358 std::string contents;
[email protected]82f84b92013-08-30 18:23:506359 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046360 EXPECT_EQ(contents, d.data_received());
6361 }
6362}
6363
[email protected]316c1e5e2012-09-12 15:17:446364TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
6365 ASSERT_TRUE(test_server_.Start());
6366
6367 TestDelegate d;
6368 {
6369 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196370 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366371 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196372 req->Start();
[email protected]255620da2013-08-19 13:14:296373 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446374
6375 EXPECT_EQ(1, d.received_redirect_count());
6376
[email protected]f7022f32014-08-21 16:32:196377 req->Cancel();
[email protected]255620da2013-08-19 13:14:296378 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446379
6380 EXPECT_EQ(1, d.response_started_count());
6381 EXPECT_EQ(0, d.bytes_received());
6382 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196383 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446384 }
6385}
6386
6387TEST_F(URLRequestTestHTTP, VaryHeader) {
6388 ASSERT_TRUE(test_server_.Start());
6389
[email protected]3b23a222013-05-15 21:33:256390 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446391 {
6392 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196393 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366394 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446395 HttpRequestHeaders headers;
6396 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196397 req->SetExtraRequestHeaders(headers);
6398 req->Start();
[email protected]255620da2013-08-19 13:14:296399 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256400
6401 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196402 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256403 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446404 }
6405
[email protected]3b23a222013-05-15 21:33:256406 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446407 {
6408 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196409 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366410 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446411 HttpRequestHeaders headers;
6412 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196413 req->SetExtraRequestHeaders(headers);
6414 req->Start();
[email protected]255620da2013-08-19 13:14:296415 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446416
[email protected]f7022f32014-08-21 16:32:196417 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256418
6419 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196420 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256421 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446422 }
6423
[email protected]3b23a222013-05-15 21:33:256424 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446425 {
6426 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196427 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366428 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446429 HttpRequestHeaders headers;
6430 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196431 req->SetExtraRequestHeaders(headers);
6432 req->Start();
[email protected]255620da2013-08-19 13:14:296433 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446434
[email protected]f7022f32014-08-21 16:32:196435 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256436
6437 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196438 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256439 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446440 }
6441}
6442
6443TEST_F(URLRequestTestHTTP, BasicAuth) {
6444 ASSERT_TRUE(test_server_.Start());
6445
6446 // populate the cache
6447 {
6448 TestDelegate d;
6449 d.set_credentials(AuthCredentials(kUser, kSecret));
6450
[email protected]f7022f32014-08-21 16:32:196451 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366452 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196453 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446454
[email protected]255620da2013-08-19 13:14:296455 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446456
6457 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6458 }
6459
6460 // repeat request with end-to-end validation. since auth-basic results in a
6461 // cachable page, we expect this test to result in a 304. in which case, the
6462 // response should be fetched from the cache.
6463 {
6464 TestDelegate d;
6465 d.set_credentials(AuthCredentials(kUser, kSecret));
6466
[email protected]f7022f32014-08-21 16:32:196467 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366468 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196469 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6470 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446471
[email protected]255620da2013-08-19 13:14:296472 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446473
6474 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6475
6476 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196477 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446478 }
6479}
6480
6481// Check that Set-Cookie headers in 401 responses are respected.
6482// http://crbug.com/6450
6483TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6484 ASSERT_TRUE(test_server_.Start());
6485
6486 GURL url_requiring_auth =
6487 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6488
6489 // Request a page that will give a 401 containing a Set-Cookie header.
6490 // Verify that when the transaction is restarted, it includes the new cookie.
6491 {
[email protected]ceefd7fd2012-11-29 00:36:246492 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446493 TestURLRequestContext context(true);
6494 context.set_network_delegate(&network_delegate);
6495 context.Init();
6496
6497 TestDelegate d;
6498 d.set_credentials(AuthCredentials(kUser, kSecret));
6499
davidben151423e2015-03-23 18:48:366500 scoped_ptr<URLRequest> r(
6501 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196502 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446503
[email protected]255620da2013-08-19 13:14:296504 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446505
6506 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6507
6508 // Make sure we sent the cookie in the restarted transaction.
6509 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6510 != std::string::npos);
6511 }
6512
6513 // Same test as above, except this time the restart is initiated earlier
6514 // (without user intervention since identity is embedded in the URL).
6515 {
[email protected]ceefd7fd2012-11-29 00:36:246516 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446517 TestURLRequestContext context(true);
6518 context.set_network_delegate(&network_delegate);
6519 context.Init();
6520
6521 TestDelegate d;
6522
6523 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186524 replacements.SetUsernameStr("user2");
6525 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446526 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6527
davidben151423e2015-03-23 18:48:366528 scoped_ptr<URLRequest> r(
6529 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196530 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446531
[email protected]255620da2013-08-19 13:14:296532 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446533
6534 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6535
6536 // Make sure we sent the cookie in the restarted transaction.
6537 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6538 != std::string::npos);
6539 }
6540}
6541
[email protected]58e32bb2013-01-21 18:23:256542// Tests that load timing works as expected with auth and the cache.
6543TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6544 ASSERT_TRUE(test_server_.Start());
6545
6546 // populate the cache
6547 {
6548 TestDelegate d;
6549 d.set_credentials(AuthCredentials(kUser, kSecret));
6550
[email protected]f7022f32014-08-21 16:32:196551 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366552 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196553 r->Start();
[email protected]58e32bb2013-01-21 18:23:256554
[email protected]255620da2013-08-19 13:14:296555 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256556
6557 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6558
6559 LoadTimingInfo load_timing_info_before_auth;
6560 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6561 &load_timing_info_before_auth));
6562 TestLoadTimingNotReused(load_timing_info_before_auth,
6563 CONNECT_TIMING_HAS_DNS_TIMES);
6564
6565 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196566 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256567 // The test server does not support keep alive sockets, so the second
6568 // request with auth should use a new socket.
6569 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6570 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6571 load_timing_info.socket_log_id);
6572 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6573 load_timing_info.connect_timing.connect_start);
6574 }
6575
[email protected]3b23a222013-05-15 21:33:256576 // Repeat request with end-to-end validation. Since auth-basic results in a
6577 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256578 // response should be fetched from the cache.
6579 {
6580 TestDelegate d;
6581 d.set_credentials(AuthCredentials(kUser, kSecret));
6582
[email protected]f7022f32014-08-21 16:32:196583 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366584 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196585 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6586 r->Start();
[email protected]58e32bb2013-01-21 18:23:256587
[email protected]255620da2013-08-19 13:14:296588 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256589
6590 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6591
6592 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196593 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256594
[email protected]3b23a222013-05-15 21:33:256595 // Since there was a request that went over the wire, the load timing
6596 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256597 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196598 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256599 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256600 }
6601}
6602
[email protected]316c1e5e2012-09-12 15:17:446603// In this test, we do a POST which the server will 302 redirect.
6604// The subsequent transaction should use GET, and should not send the
6605// Content-Type header.
6606// http://code.google.com/p/chromium/issues/detail?id=843
6607TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6608 ASSERT_TRUE(test_server_.Start());
6609
6610 const char kData[] = "hello world";
6611
6612 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196613 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366614 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196615 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076616 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446617
6618 // Set headers (some of which are specific to the POST).
6619 HttpRequestHeaders headers;
6620 headers.AddHeadersFromString(
6621 "Content-Type: multipart/form-data; "
6622 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6623 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6624 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6625 "Accept-Language: en-US,en\r\n"
6626 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6627 "Content-Length: 11\r\n"
6628 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196629 req->SetExtraRequestHeaders(headers);
6630 req->Start();
[email protected]255620da2013-08-19 13:14:296631 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446632
6633 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196634 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446635 EXPECT_EQ("text/html", mime_type);
6636
6637 const std::string& data = d.data_received();
6638
6639 // Check that the post-specific headers were stripped:
6640 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6641 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6642 EXPECT_FALSE(ContainsString(data, "Origin:"));
6643
6644 // These extra request headers should not have been stripped.
6645 EXPECT_TRUE(ContainsString(data, "Accept:"));
6646 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6647 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6648}
6649
jww5fe460ff2015-03-28 00:22:516650// The following tests check that we handle mutating the request for HTTP
6651// redirects as expected.
6652// See https://crbug.com/56373, https://crbug.com/102130, and
6653// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:446654
6655TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6656 ASSERT_TRUE(test_server_.Start());
6657
6658 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:516659 const GURL https_redirect_url =
6660 test_server_.GetURL("files/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:446661
6662 HTTPRedirectMethodTest(url, "POST", "GET", true);
6663 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6664 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516665
6666 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6667 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6668 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6669 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6670 std::string());
[email protected]316c1e5e2012-09-12 15:17:446671}
6672
6673TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6674 ASSERT_TRUE(test_server_.Start());
6675
6676 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:516677 const GURL https_redirect_url =
6678 test_server_.GetURL("files/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:446679
6680 HTTPRedirectMethodTest(url, "POST", "GET", true);
6681 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6682 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516683
6684 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6685 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6686 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6687 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6688 std::string());
[email protected]316c1e5e2012-09-12 15:17:446689}
6690
6691TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6692 ASSERT_TRUE(test_server_.Start());
6693
6694 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:516695 const GURL https_redirect_url =
6696 test_server_.GetURL("files/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:446697
6698 HTTPRedirectMethodTest(url, "POST", "GET", true);
6699 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6700 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516701
6702 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6703 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6704 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6705 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6706 std::string());
[email protected]316c1e5e2012-09-12 15:17:446707}
6708
6709TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6710 ASSERT_TRUE(test_server_.Start());
6711
6712 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:516713 const GURL https_redirect_url =
6714 test_server_.GetURL("files/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:446715
6716 HTTPRedirectMethodTest(url, "POST", "POST", true);
6717 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6718 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516719
6720 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6721 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6722 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6723 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:446724}
6725
[email protected]0a17aab32014-04-24 03:32:376726TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6727 ASSERT_TRUE(test_server_.Start());
6728
6729 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:516730 const GURL https_redirect_url =
6731 test_server_.GetURL("files/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:376732
6733 HTTPRedirectMethodTest(url, "POST", "POST", true);
6734 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6735 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516736
6737 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6738 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6739 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6740 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:376741}
6742
6743// Make sure that 308 responses without bodies are not treated as redirects.
6744// Certain legacy apis that pre-date the response code expect this behavior
6745// (Like Google Drive).
6746TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6747 ASSERT_TRUE(test_server_.Start());
6748
6749 TestDelegate d;
6750 const GURL url = test_server_.GetURL("files/308-without-location-header");
6751
davidben151423e2015-03-23 18:48:366752 scoped_ptr<URLRequest> request(
6753 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:376754
[email protected]f7022f32014-08-21 16:32:196755 request->Start();
[email protected]0a17aab32014-04-24 03:32:376756 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196757 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6758 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:376759 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196760 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:376761 EXPECT_EQ("This is not a redirect.", d.data_received());
6762}
6763
[email protected]f878230e2014-04-03 15:36:146764TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6765 ASSERT_TRUE(test_server_.Start());
6766
6767 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6768 GURL expected_url(test_server_.GetURL("echo#fragment"));
6769
6770 TestDelegate d;
6771 {
davidben151423e2015-03-23 18:48:366772 scoped_ptr<URLRequest> r(
6773 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146774
[email protected]f7022f32014-08-21 16:32:196775 r->Start();
[email protected]f878230e2014-04-03 15:36:146776 base::RunLoop().Run();
6777
[email protected]f7022f32014-08-21 16:32:196778 EXPECT_EQ(2U, r->url_chain().size());
6779 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6780 EXPECT_EQ(OK, r->status().error());
6781 EXPECT_EQ(original_url, r->original_url());
6782 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:146783 }
6784}
6785
[email protected]cba24642014-08-15 20:49:596786TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6787 ASSERT_TRUE(test_server_.Start());
6788
6789 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6790 GURL first_party_url("http://example.com");
6791
6792 TestDelegate d;
6793 {
davidben151423e2015-03-23 18:48:366794 scoped_ptr<URLRequest> r(
6795 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196796 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:596797
[email protected]f7022f32014-08-21 16:32:196798 r->Start();
[email protected]cba24642014-08-15 20:49:596799 base::RunLoop().Run();
6800
[email protected]f7022f32014-08-21 16:32:196801 EXPECT_EQ(2U, r->url_chain().size());
6802 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6803 EXPECT_EQ(OK, r->status().error());
6804 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596805 }
6806}
6807
6808TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6809 ASSERT_TRUE(test_server_.Start());
6810
6811 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6812 GURL original_first_party_url("http://example.com");
6813 GURL expected_first_party_url(test_server_.GetURL("echo"));
6814
6815 TestDelegate d;
6816 {
davidben151423e2015-03-23 18:48:366817 scoped_ptr<URLRequest> r(
6818 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196819 r->set_first_party_for_cookies(original_first_party_url);
6820 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:596821 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6822
[email protected]f7022f32014-08-21 16:32:196823 r->Start();
[email protected]cba24642014-08-15 20:49:596824 base::RunLoop().Run();
6825
[email protected]f7022f32014-08-21 16:32:196826 EXPECT_EQ(2U, r->url_chain().size());
6827 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6828 EXPECT_EQ(OK, r->status().error());
6829 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596830 }
6831}
6832
[email protected]316c1e5e2012-09-12 15:17:446833TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6834 ASSERT_TRUE(test_server_.Start());
6835
6836 const char kData[] = "hello world";
6837
6838 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196839 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366840 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196841 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076842 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446843 HttpRequestHeaders headers;
6844 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:516845 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196846 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446847
6848 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196849 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096850 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446851 AddTestInterceptor()->set_main_intercept_job(job);
6852
[email protected]f7022f32014-08-21 16:32:196853 req->Start();
[email protected]255620da2013-08-19 13:14:296854 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196855 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:446856}
6857
6858TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6859 ASSERT_TRUE(test_server_.Start());
6860
6861 const char kData[] = "hello world";
6862
6863 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196864 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366865 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196866 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076867 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446868 HttpRequestHeaders headers;
6869 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:516870 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196871 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446872
6873 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196874 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096875 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6876 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446877 AddTestInterceptor()->set_main_intercept_job(job);
6878
[email protected]f7022f32014-08-21 16:32:196879 req->Start();
[email protected]255620da2013-08-19 13:14:296880 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196881 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:446882 EXPECT_EQ(kData, d.data_received());
6883}
6884
6885// Check that default A-L header is sent.
6886TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6887 ASSERT_TRUE(test_server_.Start());
6888
[email protected]8790210c2013-12-02 05:29:536889 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:246890 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446891 TestURLRequestContext context(true);
6892 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:436893 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446894 context.Init();
6895
6896 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196897 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366898 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196899 req->Start();
[email protected]255620da2013-08-19 13:14:296900 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446901 EXPECT_EQ("en", d.data_received());
6902}
6903
6904// Check that an empty A-L header is not sent. http://crbug.com/77365.
6905TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6906 ASSERT_TRUE(test_server_.Start());
6907
[email protected]8790210c2013-12-02 05:29:536908 std::string empty_string; // Avoid most vexing parse on line below.
6909 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:246910 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446911 TestURLRequestContext context(true);
6912 context.set_network_delegate(&network_delegate);
6913 context.Init();
6914 // We override the language after initialization because empty entries
6915 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:436916 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446917
6918 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196919 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366920 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196921 req->Start();
[email protected]255620da2013-08-19 13:14:296922 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446923 EXPECT_EQ("None", d.data_received());
6924}
6925
6926// Check that if request overrides the A-L header, the default is not appended.
6927// See http://crbug.com/20894
6928TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6929 ASSERT_TRUE(test_server_.Start());
6930
6931 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196932 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366933 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446934 HttpRequestHeaders headers;
6935 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:196936 req->SetExtraRequestHeaders(headers);
6937 req->Start();
[email protected]255620da2013-08-19 13:14:296938 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446939 EXPECT_EQ(std::string("ru"), d.data_received());
6940}
6941
6942// Check that default A-E header is sent.
6943TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6944 ASSERT_TRUE(test_server_.Start());
6945
6946 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196947 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366948 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446949 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:196950 req->SetExtraRequestHeaders(headers);
6951 req->Start();
[email protected]255620da2013-08-19 13:14:296952 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446953 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6954}
6955
6956// Check that if request overrides the A-E header, the default is not appended.
6957// See http://crbug.com/47381
6958TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6959 ASSERT_TRUE(test_server_.Start());
6960
6961 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196962 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366963 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446964 HttpRequestHeaders headers;
6965 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:196966 req->SetExtraRequestHeaders(headers);
6967 req->Start();
[email protected]255620da2013-08-19 13:14:296968 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446969 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6970 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6971}
6972
[email protected]84f05432013-03-15 01:00:126973// Check that setting the A-C header sends the proper header.
6974TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:446975 ASSERT_TRUE(test_server_.Start());
6976
6977 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196978 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366979 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446980 HttpRequestHeaders headers;
6981 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:196982 req->SetExtraRequestHeaders(headers);
6983 req->Start();
[email protected]255620da2013-08-19 13:14:296984 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446985 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6986}
6987
6988// Check that default User-Agent header is sent.
6989TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6990 ASSERT_TRUE(test_server_.Start());
6991
6992 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196993 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366994 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196995 req->Start();
[email protected]255620da2013-08-19 13:14:296996 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196997 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:376998 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446999}
7000
7001// Check that if request overrides the User-Agent header,
7002// the default is not appended.
7003TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
7004 ASSERT_TRUE(test_server_.Start());
7005
7006 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197007 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367008 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447009 HttpRequestHeaders headers;
7010 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197011 req->SetExtraRequestHeaders(headers);
7012 req->Start();
[email protected]255620da2013-08-19 13:14:297013 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357014 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447015}
7016
[email protected]ee4c30d2012-11-07 15:08:437017// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7018// User-Agent header to be sent but does not send the Accept-Language and
7019// Accept-Charset headers.
7020TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
7021 ASSERT_TRUE(test_server_.Start());
7022
[email protected]ceefd7fd2012-11-29 00:36:247023 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437024 TestURLRequestContext context(true);
7025 context.set_network_delegate(&network_delegate);
7026 context.Init();
7027 // We override the HttpUserAgentSettings after initialization because empty
7028 // entries get overridden by Init().
7029 context.set_http_user_agent_settings(NULL);
7030
7031 struct {
7032 const char* request;
7033 const char* expected_response;
7034 } tests[] = { { "echoheader?Accept-Language", "None" },
7035 { "echoheader?Accept-Charset", "None" },
7036 { "echoheader?User-Agent", "" } };
7037
viettrungluue4a8b882014-10-16 06:17:387038 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437039 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197040 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:367041 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197042 req->Start();
[email protected]255620da2013-08-19 13:14:297043 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437044 EXPECT_EQ(tests[i].expected_response, d.data_received())
7045 << " Request = \"" << tests[i].request << "\"";
7046 }
7047}
7048
[email protected]5033ab82013-03-22 20:17:467049// Make sure that URLRequest passes on its priority updates to
7050// newly-created jobs after the first one.
7051TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
7052 ASSERT_TRUE(test_server_.Start());
7053
7054 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197055 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367056 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197057 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467058
7059 scoped_refptr<URLRequestRedirectJob> redirect_job =
7060 new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197061 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:097062 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:507063 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:467064
[email protected]f7022f32014-08-21 16:32:197065 req->SetPriority(LOW);
7066 req->Start();
7067 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467068
7069 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:197070 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:507071 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:467072
7073 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297074 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:467075 EXPECT_EQ(LOW, job->priority());
7076}
7077
[email protected]80abdad2014-03-15 00:20:547078// Check that creating a network request while entering/exiting suspend mode
7079// fails as it should. This is the only case where an HttpTransactionFactory
7080// does not return an HttpTransaction.
7081TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7082 // Create a new HttpNetworkLayer that thinks it's suspended.
7083 HttpNetworkSession::Params params;
7084 params.host_resolver = default_context_.host_resolver();
7085 params.cert_verifier = default_context_.cert_verifier();
7086 params.transport_security_state = default_context_.transport_security_state();
7087 params.proxy_service = default_context_.proxy_service();
7088 params.ssl_config_service = default_context_.ssl_config_service();
7089 params.http_auth_handler_factory =
7090 default_context_.http_auth_handler_factory();
7091 params.network_delegate = &default_network_delegate_;
7092 params.http_server_properties = default_context_.http_server_properties();
mmenkee65e7af2015-10-13 17:16:427093 HttpNetworkSession network_session(params);
[email protected]80abdad2014-03-15 00:20:547094 scoped_ptr<HttpNetworkLayer> network_layer(
mmenkee65e7af2015-10-13 17:16:427095 new HttpNetworkLayer(&network_session));
[email protected]80abdad2014-03-15 00:20:547096 network_layer->OnSuspend();
7097
7098 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
mmenkee65e7af2015-10-13 17:16:427099 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547100
7101 TestURLRequestContext context(true);
7102 context.set_http_transaction_factory(&http_cache);
7103 context.Init();
7104
7105 TestDelegate d;
davidben151423e2015-03-23 18:48:367106 scoped_ptr<URLRequest> req(
7107 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197108 req->Start();
[email protected]80abdad2014-03-15 00:20:547109 base::RunLoop().Run();
7110
7111 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197112 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7113 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547114}
7115
7116// Check that creating a network request while entering/exiting suspend mode
7117// fails as it should in the case there is no cache. This is the only case
7118// where an HttpTransactionFactory does not return an HttpTransaction.
7119TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
7120 // Create a new HttpNetworkLayer that thinks it's suspended.
7121 HttpNetworkSession::Params params;
7122 params.host_resolver = default_context_.host_resolver();
7123 params.cert_verifier = default_context_.cert_verifier();
7124 params.transport_security_state = default_context_.transport_security_state();
7125 params.proxy_service = default_context_.proxy_service();
7126 params.ssl_config_service = default_context_.ssl_config_service();
7127 params.http_auth_handler_factory =
7128 default_context_.http_auth_handler_factory();
7129 params.network_delegate = &default_network_delegate_;
7130 params.http_server_properties = default_context_.http_server_properties();
mmenkee65e7af2015-10-13 17:16:427131 HttpNetworkSession network_session(params);
7132 HttpNetworkLayer network_layer(&network_session);
[email protected]80abdad2014-03-15 00:20:547133 network_layer.OnSuspend();
7134
7135 TestURLRequestContext context(true);
7136 context.set_http_transaction_factory(&network_layer);
7137 context.Init();
7138
7139 TestDelegate d;
davidben151423e2015-03-23 18:48:367140 scoped_ptr<URLRequest> req(
7141 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197142 req->Start();
[email protected]80abdad2014-03-15 00:20:547143 base::RunLoop().Run();
7144
7145 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197146 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7147 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547148}
7149
ttuttlec0c828492015-05-15 01:25:557150TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
7151 ASSERT_TRUE(test_server_.Start());
7152
7153 TestDelegate d;
7154 GURL test_url(test_server_.GetURL(std::string()));
7155 scoped_ptr<URLRequest> req(
7156 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7157
7158 req->Start();
7159 base::RunLoop().Run();
7160
7161 EXPECT_TRUE(req->response_info().network_accessed);
7162}
7163
7164TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
7165 ASSERT_TRUE(test_server_.Start());
7166
7167 // Populate the cache.
7168 TestDelegate d;
7169 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
7170 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
7171 req->Start();
7172 base::RunLoop().Run();
7173
7174 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7175 EXPECT_TRUE(req->response_info().network_accessed);
7176 EXPECT_FALSE(req->response_info().was_cached);
7177
7178 req = default_context_.CreateRequest(test_server_.GetURL("cachetime"),
7179 DEFAULT_PRIORITY, &d);
7180 req->Start();
7181 base::RunLoop().Run();
7182
7183 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7184 EXPECT_FALSE(req->response_info().network_accessed);
7185 EXPECT_TRUE(req->response_info().was_cached);
7186}
7187
7188TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
7189 ASSERT_TRUE(test_server_.Start());
7190
7191 TestDelegate d;
7192 GURL test_url(test_server_.GetURL(std::string()));
7193 scoped_ptr<URLRequest> req(
7194 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7195 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7196
7197 req->Start();
7198 base::RunLoop().Run();
7199
7200 EXPECT_FALSE(req->response_info().network_accessed);
7201}
7202
bengr1bf8e942014-11-07 01:36:507203class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7204 public:
7205 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7206 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7207 // tests into the factory tests.
7208 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7209 }
7210
7211 void SetUpFactory() override {
7212 interceptor_ = new MockURLRequestInterceptor();
7213 job_factory_.reset(new URLRequestInterceptingJobFactory(
7214 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
7215 }
7216
7217 MockURLRequestInterceptor* interceptor() const {
7218 return interceptor_;
7219 }
7220
7221 private:
7222 MockURLRequestInterceptor* interceptor_;
7223};
7224
7225TEST_F(URLRequestInterceptorTestHTTP,
7226 NetworkDelegateNotificationOnRedirectIntercept) {
7227 interceptor()->set_intercept_redirect(true);
7228 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7229 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7230
7231 ASSERT_TRUE(test_server()->Start());
7232
7233 TestDelegate d;
7234 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:367235 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507236 req->Start();
7237 base::RunLoop().Run();
7238
7239 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7240 // Check we got one good response
7241 EXPECT_TRUE(req->status().is_success());
7242 if (req->status().is_success())
7243 EXPECT_EQ(200, req->response_headers()->response_code());
7244
7245 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7246 EXPECT_EQ(1, d.response_started_count());
7247 EXPECT_EQ(0, d.received_redirect_count());
7248
7249 EXPECT_EQ(1, default_network_delegate()->created_requests());
7250 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7251 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7252}
7253
7254TEST_F(URLRequestInterceptorTestHTTP,
7255 NetworkDelegateNotificationOnErrorIntercept) {
7256 // Intercept that error and respond with an OK response.
7257 interceptor()->set_intercept_final_response(true);
7258 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7259 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7260 default_network_delegate()->set_can_be_intercepted_on_error(true);
7261
7262 ASSERT_TRUE(test_server()->Start());
7263
7264 TestDelegate d;
7265 scoped_ptr<URLRequest> req(default_context().CreateRequest(
7266 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:367267 &d));
bengr1bf8e942014-11-07 01:36:507268 req->set_method("GET");
7269 req->Start();
7270 base::RunLoop().Run();
7271
7272 EXPECT_TRUE(interceptor()->did_intercept_final());
7273
7274 // Check we received one good response.
7275 EXPECT_TRUE(req->status().is_success());
7276 if (req->status().is_success())
7277 EXPECT_EQ(200, req->response_headers()->response_code());
7278 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7279 EXPECT_EQ(1, d.response_started_count());
7280 EXPECT_EQ(0, d.received_redirect_count());
7281
7282 EXPECT_EQ(1, default_network_delegate()->created_requests());
7283 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7284 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7285}
7286
7287TEST_F(URLRequestInterceptorTestHTTP,
7288 NetworkDelegateNotificationOnResponseIntercept) {
7289 // Intercept that error and respond with an OK response.
7290 interceptor()->set_intercept_final_response(true);
7291
7292 // Intercept with a real URLRequestHttpJob.
7293 interceptor()->set_use_url_request_http_job(true);
7294
7295 ASSERT_TRUE(test_server()->Start());
7296
7297 TestDelegate d;
7298 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:367299 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507300 req->set_method("GET");
7301 req->Start();
7302 base::RunLoop().Run();
7303
7304 EXPECT_TRUE(interceptor()->did_intercept_final());
7305
7306 // Check we received one good response.
7307 EXPECT_TRUE(req->status().is_success());
7308 if (req->status().is_success())
7309 EXPECT_EQ(200, req->response_headers()->response_code());
7310 EXPECT_EQ("hello", d.data_received());
7311 EXPECT_EQ(1, d.response_started_count());
7312 EXPECT_EQ(0, d.received_redirect_count());
7313
7314 EXPECT_EQ(1, default_network_delegate()->created_requests());
7315 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7316 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7317}
7318
mkwst0c5eab872014-11-21 14:18:547319class URLRequestTestReferrerPolicy : public URLRequestTest {
7320 public:
7321 URLRequestTestReferrerPolicy() {}
7322
7323 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
7324 origin_server_.reset(new SpawnedTestServer(
7325 origin_type, SpawnedTestServer::kLocalhost,
7326 origin_type == SpawnedTestServer::TYPE_HTTPS
7327 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477328 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547329 ASSERT_TRUE(origin_server_->Start());
7330 }
7331
7332 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
7333 SpawnedTestServer::Type destination_type) {
7334 origin_server_.reset(new SpawnedTestServer(
7335 origin_type, SpawnedTestServer::kLocalhost,
7336 origin_type == SpawnedTestServer::TYPE_HTTPS
7337 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477338 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547339 ASSERT_TRUE(origin_server_->Start());
7340
7341 destination_server_.reset(new SpawnedTestServer(
7342 destination_type, SpawnedTestServer::kLocalhost,
7343 destination_type == SpawnedTestServer::TYPE_HTTPS
7344 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477345 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547346 ASSERT_TRUE(destination_server_->Start());
7347 }
7348
7349 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7350 const GURL& referrer,
7351 const GURL& expected) {
7352 // Create and execute the request: we'll only have a |destination_server_|
7353 // if the origins are meant to be distinct. Otherwise, we'll use the
7354 // |origin_server_| for both endpoints.
7355 GURL destination_url =
7356 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
7357 : origin_server_->GetURL("echoheader?Referer");
7358 GURL origin_url =
7359 origin_server_->GetURL("server-redirect?" + destination_url.spec());
7360
7361 TestDelegate d;
7362 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367363 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547364 req->set_referrer_policy(policy);
7365 req->SetReferrer(referrer.spec());
7366 req->Start();
7367 base::RunLoop().Run();
7368
7369 EXPECT_EQ(1, d.response_started_count());
7370 EXPECT_EQ(1, d.received_redirect_count());
7371 EXPECT_EQ(destination_url, req->url());
7372 EXPECT_TRUE(req->status().is_success());
7373 EXPECT_EQ(200, req->response_headers()->response_code());
7374
7375 EXPECT_EQ(expected.spec(), req->referrer());
7376 if (expected.is_empty())
7377 EXPECT_EQ("None", d.data_received());
7378 else
7379 EXPECT_EQ(expected.spec(), d.data_received());
7380 }
7381
7382 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
7383
7384 private:
7385 scoped_ptr<SpawnedTestServer> origin_server_;
7386 scoped_ptr<SpawnedTestServer> destination_server_;
7387};
7388
7389TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
7390 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
7391
7392 VerifyReferrerAfterRedirect(
7393 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7394 origin_server()->GetURL("path/to/file.html"),
7395 origin_server()->GetURL("path/to/file.html"));
7396
7397 VerifyReferrerAfterRedirect(
7398 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7399 origin_server()->GetURL("path/to/file.html"),
7400 origin_server()->GetURL("path/to/file.html"));
7401
7402 VerifyReferrerAfterRedirect(
7403 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7404 origin_server()->GetURL("path/to/file.html"),
7405 origin_server()->GetURL("path/to/file.html"));
7406
7407 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7408 origin_server()->GetURL("path/to/file.html"),
7409 origin_server()->GetURL("path/to/file.html"));
7410}
7411
tfarinae04a95b2015-09-18 22:48:127412// Can't spin up more than one SpawnedTestServer on Android.
7413#if defined(OS_ANDROID)
7414#define MAYBE_HTTPToCrossOriginHTTP DISABLED_HTTPToCrosOriginHTTP
7415#else
7416#define MAYBE_HTTPToCrossOriginHTTP HTTPToCrossOriginHTTP
7417#endif
7418TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPToCrossOriginHTTP) {
mkwst0c5eab872014-11-21 14:18:547419 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7420 SpawnedTestServer::TYPE_HTTP);
7421
7422 VerifyReferrerAfterRedirect(
7423 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7424 origin_server()->GetURL("path/to/file.html"),
7425 origin_server()->GetURL("path/to/file.html"));
7426
7427 VerifyReferrerAfterRedirect(
7428 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7429 origin_server()->GetURL("path/to/file.html"),
7430 origin_server()->GetURL(std::string()));
7431
7432 VerifyReferrerAfterRedirect(
7433 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7434 origin_server()->GetURL("path/to/file.html"),
7435 origin_server()->GetURL(std::string()));
7436
7437 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7438 origin_server()->GetURL("path/to/file.html"),
7439 origin_server()->GetURL("path/to/file.html"));
7440}
7441
7442TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
7443 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
7444
7445 VerifyReferrerAfterRedirect(
7446 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7447 origin_server()->GetURL("path/to/file.html"),
7448 origin_server()->GetURL("path/to/file.html"));
7449
7450 VerifyReferrerAfterRedirect(
7451 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7452 origin_server()->GetURL("path/to/file.html"),
7453 origin_server()->GetURL("path/to/file.html"));
7454
7455 VerifyReferrerAfterRedirect(
7456 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7457 origin_server()->GetURL("path/to/file.html"),
7458 origin_server()->GetURL("path/to/file.html"));
7459
7460 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7461 origin_server()->GetURL("path/to/file.html"),
7462 origin_server()->GetURL("path/to/file.html"));
7463}
7464
tfarinae04a95b2015-09-18 22:48:127465// Can't spin up more than one SpawnedTestServer on Android.
7466#if defined(OS_ANDROID)
7467#define MAYBE_HTTPSToCrossOriginHTTPS DISABLED_HTTPSToCrosOriginHTTPS
7468#else
7469#define MAYBE_HTTPSToCrossOriginHTTPS HTTPSToCrossOriginHTTPS
7470#endif
7471TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPSToCrossOriginHTTPS) {
mkwst0c5eab872014-11-21 14:18:547472 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7473 SpawnedTestServer::TYPE_HTTPS);
7474
7475 VerifyReferrerAfterRedirect(
7476 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7477 origin_server()->GetURL("path/to/file.html"),
7478 origin_server()->GetURL("path/to/file.html"));
7479
7480 VerifyReferrerAfterRedirect(
7481 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7482 origin_server()->GetURL("path/to/file.html"),
7483 origin_server()->GetURL(std::string()));
7484
7485 VerifyReferrerAfterRedirect(
7486 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7487 origin_server()->GetURL("path/to/file.html"),
7488 origin_server()->GetURL(std::string()));
7489
7490 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7491 origin_server()->GetURL("path/to/file.html"),
7492 origin_server()->GetURL("path/to/file.html"));
7493}
7494
tfarinae04a95b2015-09-18 22:48:127495// Can't spin up more than one SpawnedTestServer on Android.
7496#if defined(OS_ANDROID)
7497#define MAYBE_HTTPToHTTPS DISABLED_HTTPToHTTPS
7498#else
7499#define MAYBE_HTTPToHTTPS HTTPToHTTPS
7500#endif
7501TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPToHTTPS) {
mkwst0c5eab872014-11-21 14:18:547502 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7503 SpawnedTestServer::TYPE_HTTPS);
7504
7505 VerifyReferrerAfterRedirect(
7506 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7507 origin_server()->GetURL("path/to/file.html"),
7508 origin_server()->GetURL("path/to/file.html"));
7509
7510 VerifyReferrerAfterRedirect(
7511 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7512 origin_server()->GetURL("path/to/file.html"),
7513 origin_server()->GetURL(std::string()));
7514
7515 VerifyReferrerAfterRedirect(
7516 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7517 origin_server()->GetURL("path/to/file.html"),
7518 origin_server()->GetURL(std::string()));
7519
7520 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7521 origin_server()->GetURL("path/to/file.html"),
7522 origin_server()->GetURL("path/to/file.html"));
7523}
7524
tfarinae04a95b2015-09-18 22:48:127525// Can't spin up more than one SpawnedTestServer on Android.
7526#if defined(OS_ANDROID)
7527#define MAYBE_HTTPSToHTTP DISABLED_HTTPSToHTTP
7528#else
7529#define MAYBE_HTTPSToHTTP HTTPSToHTTP
7530#endif
7531TEST_F(URLRequestTestReferrerPolicy, MAYBE_HTTPSToHTTP) {
mkwst0c5eab872014-11-21 14:18:547532 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7533 SpawnedTestServer::TYPE_HTTP);
7534
7535 VerifyReferrerAfterRedirect(
7536 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7537 origin_server()->GetURL("path/to/file.html"), GURL());
7538
7539 VerifyReferrerAfterRedirect(
7540 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7541 origin_server()->GetURL("path/to/file.html"), GURL());
7542
7543 VerifyReferrerAfterRedirect(
7544 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7545 origin_server()->GetURL("path/to/file.html"),
7546 origin_server()->GetURL(std::string()));
7547
7548 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7549 origin_server()->GetURL("path/to/file.html"),
7550 origin_server()->GetURL("path/to/file.html"));
7551}
7552
[email protected]73e0bba2009-02-19 22:57:097553class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507554 public:
[email protected]ef2bf422012-05-11 03:27:097555 HTTPSRequestTest() : default_context_(true) {
7556 default_context_.set_network_delegate(&default_network_delegate_);
7557 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507558 }
dcheng67be2b1f2014-10-27 21:47:297559 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507560
7561 protected:
[email protected]ceefd7fd2012-11-29 00:36:247562 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097563 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467564};
7565
[email protected]c044616e2013-02-20 02:01:267566TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227567 SpawnedTestServer test_server(
7568 SpawnedTestServer::TYPE_HTTPS,
7569 SpawnedTestServer::kLocalhost,
7570 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117571 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467572
[email protected]ea224582008-12-07 20:25:467573 TestDelegate d;
7574 {
[email protected]f7022f32014-08-21 16:32:197575 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367576 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197577 r->Start();
7578 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467579
[email protected]255620da2013-08-19 13:14:297580 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467581
7582 EXPECT_EQ(1, d.response_started_count());
7583 EXPECT_FALSE(d.received_data_before_response());
7584 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197585 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197586 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197587 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197588 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197589 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467590 }
[email protected]ea224582008-12-07 20:25:467591}
7592
[email protected]5774ada2010-07-15 06:30:547593TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227594 SpawnedTestServer::SSLOptions ssl_options(
7595 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7596 SpawnedTestServer test_server(
7597 SpawnedTestServer::TYPE_HTTPS,
7598 ssl_options,
7599 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117600 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337601
7602 bool err_allowed = true;
7603 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7604 TestDelegate d;
7605 {
7606 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197607 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367608 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337609
[email protected]f7022f32014-08-21 16:32:197610 r->Start();
7611 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337612
[email protected]255620da2013-08-19 13:14:297613 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337614
7615 EXPECT_EQ(1, d.response_started_count());
7616 EXPECT_FALSE(d.received_data_before_response());
7617 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177618 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337619 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197620 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177621 } else {
[email protected]bacff652009-03-31 17:50:337622 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177623 }
[email protected]bacff652009-03-31 17:50:337624 }
7625 }
7626}
7627
[email protected]5774ada2010-07-15 06:30:547628TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227629 SpawnedTestServer::SSLOptions ssl_options(
7630 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7631 SpawnedTestServer test_server(
7632 SpawnedTestServer::TYPE_HTTPS,
7633 ssl_options,
7634 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117635 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337636
7637 // Iterate from false to true, just so that we do the opposite of the
7638 // previous test in order to increase test coverage.
7639 bool err_allowed = false;
7640 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7641 TestDelegate d;
7642 {
7643 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197644 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367645 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337646
[email protected]f7022f32014-08-21 16:32:197647 r->Start();
7648 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337649
[email protected]255620da2013-08-19 13:14:297650 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337651
7652 EXPECT_EQ(1, d.response_started_count());
7653 EXPECT_FALSE(d.received_data_before_response());
7654 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177655 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337656 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197657 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177658 } else {
[email protected]bacff652009-03-31 17:50:337659 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177660 }
[email protected]bacff652009-03-31 17:50:337661 }
7662 }
7663}
[email protected]73e0bba2009-02-19 22:57:097664
davidbena4c9d062015-04-03 22:34:257665// Tests that servers which require a deprecated cipher suite still work.
7666TEST_F(HTTPSRequestTest, CipherFallbackTest) {
vishal.b62985ca92015-04-17 08:45:517667 TestNetLog net_log;
davidbena4c9d062015-04-03 22:34:257668 default_context_.set_net_log(&net_log);
7669
7670 SpawnedTestServer::SSLOptions ssl_options;
7671 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
7672 SpawnedTestServer test_server(
7673 SpawnedTestServer::TYPE_HTTPS, ssl_options,
7674 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7675 ASSERT_TRUE(test_server.Start());
7676
7677 TestDelegate d;
7678 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7679 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7680 r->Start();
7681 EXPECT_TRUE(r->is_pending());
7682
7683 base::RunLoop().Run();
7684
7685 EXPECT_EQ(1, d.response_started_count());
7686 EXPECT_FALSE(d.received_data_before_response());
7687 EXPECT_NE(0, d.bytes_received());
7688 CheckSSLInfo(r->ssl_info());
7689 EXPECT_EQ(test_server.host_port_pair().host(), r->GetSocketAddress().host());
7690 EXPECT_EQ(test_server.host_port_pair().port(), r->GetSocketAddress().port());
7691
7692 // No version downgrade should have been necessary.
7693 EXPECT_FALSE(r->ssl_info().connection_status &
7694 SSL_CONNECTION_VERSION_FALLBACK);
davidben6cacd572015-09-29 22:24:107695 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_2,
davidbena4c9d062015-04-03 22:34:257696 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
7697
mmenke43758e62015-05-04 21:09:467698 TestNetLogEntry::List entries;
davidbena4c9d062015-04-03 22:34:257699 net_log.GetEntries(&entries);
7700 ExpectLogContainsSomewhere(entries, 0, NetLog::TYPE_SSL_CIPHER_FALLBACK,
7701 NetLog::PHASE_NONE);
7702}
7703
[email protected]316c1e5e2012-09-12 15:17:447704// This tests that a load of www.google.com with a certificate error sets
7705// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7706// the interstitial to be fatal.
7707TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227708 SpawnedTestServer::SSLOptions ssl_options(
7709 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7710 SpawnedTestServer test_server(
7711 SpawnedTestServer::TYPE_HTTPS,
7712 ssl_options,
7713 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447714 ASSERT_TRUE(test_server.Start());
7715
7716 // We require that the URL be www.google.com in order to pick up the
7717 // preloaded HSTS entries in the TransportSecurityState. This means that we
7718 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247719 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447720
7721 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247722 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447723 TestURLRequestContext context(true);
7724 context.set_network_delegate(&network_delegate);
7725 context.set_host_resolver(&host_resolver);
7726 TransportSecurityState transport_security_state;
7727 context.set_transport_security_state(&transport_security_state);
7728 context.Init();
7729
7730 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197731 scoped_ptr<URLRequest> r(context.CreateRequest(
7732 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367733 test_server.host_port_pair().port())),
7734 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447735
[email protected]f7022f32014-08-21 16:32:197736 r->Start();
7737 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447738
[email protected]255620da2013-08-19 13:14:297739 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447740
7741 EXPECT_EQ(1, d.response_started_count());
7742 EXPECT_FALSE(d.received_data_before_response());
7743 EXPECT_TRUE(d.have_certificate_errors());
7744 EXPECT_TRUE(d.certificate_errors_are_fatal());
7745}
7746
7747// This tests that cached HTTPS page loads do not cause any updates to the
7748// TransportSecurityState.
7749TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7750 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7751 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227752 SpawnedTestServer::SSLOptions ssl_options(
7753 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7754 SpawnedTestServer test_server(
7755 SpawnedTestServer::TYPE_HTTPS,
7756 ssl_options,
7757 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447758 ASSERT_TRUE(test_server.Start());
7759
[email protected]9e6968d2014-05-07 21:46:267760 // We require that the URL be www.google.com in order to pick up the static
7761 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7762 // that we have to use a MockHostResolver in order to direct www.google.com to
7763 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447764
7765 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247766 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447767 TestURLRequestContext context(true);
7768 context.set_network_delegate(&network_delegate);
7769 context.set_host_resolver(&host_resolver);
7770 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267771
martijnc0d6b622015-06-30 19:14:407772 TransportSecurityState::STSState static_sts_state;
7773 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:267774 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:407775 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:447776 context.set_transport_security_state(&transport_security_state);
7777 context.Init();
7778
martijnc0d6b622015-06-30 19:14:407779 TransportSecurityState::STSState dynamic_sts_state;
7780 TransportSecurityState::PKPState dynamic_pkp_state;
7781 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
7782 &dynamic_sts_state));
7783 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
7784 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:267785
[email protected]316c1e5e2012-09-12 15:17:447786 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197787 scoped_ptr<URLRequest> r(context.CreateRequest(
7788 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367789 test_server.host_port_pair().port())),
7790 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447791
[email protected]f7022f32014-08-21 16:32:197792 r->Start();
7793 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447794
[email protected]255620da2013-08-19 13:14:297795 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447796
7797 EXPECT_EQ(1, d.response_started_count());
7798 EXPECT_FALSE(d.received_data_before_response());
7799 EXPECT_TRUE(d.have_certificate_errors());
7800 EXPECT_TRUE(d.certificate_errors_are_fatal());
7801
[email protected]9e6968d2014-05-07 21:46:267802 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:407803 TransportSecurityState::STSState new_static_sts_state;
7804 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:267805 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:407806 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
7807 TransportSecurityState::STSState new_dynamic_sts_state;
7808 TransportSecurityState::PKPState new_dynamic_pkp_state;
7809 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
7810 "www.google.com", &new_dynamic_sts_state));
7811 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
7812 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:267813
martijnc0d6b622015-06-30 19:14:407814 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
7815 EXPECT_EQ(new_static_sts_state.include_subdomains,
7816 static_sts_state.include_subdomains);
7817 EXPECT_EQ(new_static_pkp_state.include_subdomains,
7818 static_pkp_state.include_subdomains);
7819 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.spki_hashes,
7820 static_pkp_state.spki_hashes));
7821 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.bad_spki_hashes,
7822 static_pkp_state.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:447823}
7824
[email protected]8ccc69f2012-11-28 19:52:147825// Make sure HSTS preserves a POST request's method and body.
7826TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7827 static const char kData[] = "hello world";
7828
[email protected]ce7d0cbc2013-05-03 18:57:227829 SpawnedTestServer::SSLOptions ssl_options(
7830 SpawnedTestServer::SSLOptions::CERT_OK);
7831 SpawnedTestServer test_server(
7832 SpawnedTestServer::TYPE_HTTPS,
7833 ssl_options,
7834 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:147835 ASSERT_TRUE(test_server.Start());
7836
7837
7838 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7839 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:227840 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7841 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:147842 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:147843
7844 // Force https for www.somewhere.com.
7845 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:207846 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7847 bool include_subdomains = false;
7848 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7849 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:147850
7851 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7852
7853 TestURLRequestContext context(true);
7854 context.set_host_resolver(&host_resolver);
7855 context.set_transport_security_state(&transport_security_state);
7856 context.set_network_delegate(&network_delegate);
7857 context.Init();
7858
7859 TestDelegate d;
7860 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7861 // cause a certificate error. Ignore the error.
7862 d.set_allow_certificate_errors(true);
7863
[email protected]f7022f32014-08-21 16:32:197864 scoped_ptr<URLRequest> req(context.CreateRequest(
7865 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:367866 test_server.host_port_pair().port())),
7867 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197868 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077869 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:147870
[email protected]f7022f32014-08-21 16:32:197871 req->Start();
[email protected]255620da2013-08-19 13:14:297872 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:147873
[email protected]f7022f32014-08-21 16:32:197874 EXPECT_EQ("https", req->url().scheme());
7875 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:147876 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:407877
7878 LoadTimingInfo load_timing_info;
7879 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7880 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7881 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:147882}
7883
rob4e0be1f2014-09-11 23:40:227884// Make sure that the CORS headers are added to cross-origin HSTS redirects.
7885TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7886 static const char kOriginHeaderValue[] = "http://www.example.com";
7887
7888 SpawnedTestServer::SSLOptions ssl_options(
7889 SpawnedTestServer::SSLOptions::CERT_OK);
7890 SpawnedTestServer test_server(
7891 SpawnedTestServer::TYPE_HTTPS,
7892 ssl_options,
7893 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7894 ASSERT_TRUE(test_server.Start());
7895
7896 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7897 // address, so a MockHostResolver is needed to redirect example.net to the
7898 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7899 MockHostResolver host_resolver;
7900
7901 TransportSecurityState transport_security_state;
7902 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7903 bool include_subdomains = false;
7904 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7905
7906 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7907
7908 MockCertVerifier cert_verifier;
7909 cert_verifier.set_default_result(OK);
7910
7911 TestURLRequestContext context(true);
7912 context.set_host_resolver(&host_resolver);
7913 context.set_transport_security_state(&transport_security_state);
7914 context.set_network_delegate(&network_delegate);
7915 context.set_cert_verifier(&cert_verifier);
7916 context.Init();
7917
7918 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7919 test_server.host_port_pair().port()));
7920 url::Replacements<char> replacements;
7921 const char kNewScheme[] = "https";
7922 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7923 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7924
7925 TestDelegate d;
7926 // Quit on redirect to allow response header inspection upon redirect.
7927 d.set_quit_on_redirect(true);
7928
davidben151423e2015-03-23 18:48:367929 scoped_ptr<URLRequest> req(
7930 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:227931 // Set Origin header to simulate a cross-origin request.
7932 HttpRequestHeaders request_headers;
7933 request_headers.SetHeader("Origin", kOriginHeaderValue);
7934 req->SetExtraRequestHeaders(request_headers);
7935
7936 req->Start();
7937 base::RunLoop().Run();
7938
7939 EXPECT_EQ(1, d.received_redirect_count());
7940
7941 const HttpResponseHeaders* headers = req->response_headers();
7942 std::string redirect_location;
7943 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7944 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7945
7946 std::string received_cors_header;
7947 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7948 &received_cors_header));
7949 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7950}
7951
Adam Ricecb76ac62015-02-20 05:33:257952// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
7953// are performed in net/websockets/websocket_end_to_end_test.cc.
7954TEST(WebSocketURLRequestTest, HSTSApplied) {
7955 TestNetworkDelegate network_delegate;
7956 TransportSecurityState transport_security_state;
7957 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7958 bool include_subdomains = false;
7959 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7960 TestURLRequestContext context(true);
7961 context.set_transport_security_state(&transport_security_state);
7962 context.set_network_delegate(&network_delegate);
7963 context.Init();
7964 GURL ws_url("ws://example.net/echo");
7965 TestDelegate delegate;
7966 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367967 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:257968 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
7969 EXPECT_TRUE(ws_url.SchemeIs("wss"));
7970}
7971
[email protected]316c1e5e2012-09-12 15:17:447972namespace {
7973
7974class SSLClientAuthTestDelegate : public TestDelegate {
7975 public:
7976 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7977 }
dchengb03027d2014-10-21 12:00:207978 void OnCertificateRequested(URLRequest* request,
7979 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:447980 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:177981 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:447982 }
7983 int on_certificate_requested_count() {
7984 return on_certificate_requested_count_;
7985 }
7986 private:
7987 int on_certificate_requested_count_;
7988};
7989
7990} // namespace
7991
7992// TODO(davidben): Test the rest of the code. Specifically,
7993// - Filtering which certificates to select.
7994// - Sending a certificate back.
7995// - Getting a certificate request in an SSL renegotiation sending the
7996// HTTP request.
7997TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227998 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447999 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:228000 SpawnedTestServer test_server(
8001 SpawnedTestServer::TYPE_HTTPS,
8002 ssl_options,
8003 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448004 ASSERT_TRUE(test_server.Start());
8005
8006 SSLClientAuthTestDelegate d;
8007 {
[email protected]f7022f32014-08-21 16:32:198008 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368009 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448010
[email protected]f7022f32014-08-21 16:32:198011 r->Start();
8012 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448013
[email protected]255620da2013-08-19 13:14:298014 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448015
8016 EXPECT_EQ(1, d.on_certificate_requested_count());
8017 EXPECT_FALSE(d.received_data_before_response());
8018 EXPECT_EQ(0, d.bytes_received());
8019
8020 // Send no certificate.
8021 // TODO(davidben): Get temporary client cert import (with keys) working on
8022 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:198023 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:448024
[email protected]255620da2013-08-19 13:14:298025 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448026
8027 EXPECT_EQ(1, d.response_started_count());
8028 EXPECT_FALSE(d.received_data_before_response());
8029 EXPECT_NE(0, d.bytes_received());
8030 }
8031}
8032
8033TEST_F(HTTPSRequestTest, ResumeTest) {
8034 // Test that we attempt a session resume when making two connections to the
8035 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228036 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448037 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228038 SpawnedTestServer test_server(
8039 SpawnedTestServer::TYPE_HTTPS,
8040 ssl_options,
8041 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448042 ASSERT_TRUE(test_server.Start());
8043
8044 SSLClientSocket::ClearSessionCache();
8045
8046 {
8047 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198048 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368049 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448050
[email protected]f7022f32014-08-21 16:32:198051 r->Start();
8052 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448053
[email protected]255620da2013-08-19 13:14:298054 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448055
8056 EXPECT_EQ(1, d.response_started_count());
8057 }
8058
8059 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8060 CloseAllConnections();
8061
8062 {
8063 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198064 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368065 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448066
[email protected]f7022f32014-08-21 16:32:198067 r->Start();
8068 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448069
[email protected]255620da2013-08-19 13:14:298070 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448071
8072 // The response will look like;
8073 // insert abc
8074 // lookup abc
8075 // insert xyz
8076 //
8077 // With a newline at the end which makes the split think that there are
8078 // four lines.
8079
8080 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298081 std::vector<std::string> lines = base::SplitString(
8082 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448083 ASSERT_EQ(4u, lines.size()) << d.data_received();
8084
8085 std::string session_id;
8086
8087 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298088 std::vector<std::string> parts = base::SplitString(
8089 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448090 ASSERT_EQ(2u, parts.size());
8091 if (i == 0) {
8092 EXPECT_EQ("insert", parts[0]);
8093 session_id = parts[1];
8094 } else {
8095 EXPECT_EQ("lookup", parts[0]);
8096 EXPECT_EQ(session_id, parts[1]);
8097 }
8098 }
8099 }
8100}
8101
Adam Langley32352ad2014-10-14 22:31:008102// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8103// the result of fetching "ssl-session-cache" from the test server, indicates
8104// that exactly two different sessions were inserted, with no lookups etc.
8105static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298106 std::vector<std::string> lines = base::SplitString(
8107 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008108 ASSERT_EQ(3u, lines.size()) << session_info;
8109
8110 std::string session_id;
8111 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298112 std::vector<std::string> parts = base::SplitString(
8113 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008114 ASSERT_EQ(2u, parts.size());
8115 EXPECT_EQ("insert", parts[0]);
8116 if (i == 0) {
8117 session_id = parts[1];
8118 } else {
8119 EXPECT_NE(session_id, parts[1]);
8120 }
8121 }
8122}
8123
[email protected]316c1e5e2012-09-12 15:17:448124TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8125 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8126 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228127 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448128 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228129 SpawnedTestServer test_server(
8130 SpawnedTestServer::TYPE_HTTPS,
8131 ssl_options,
8132 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448133 ASSERT_TRUE(test_server.Start());
8134
8135 SSLClientSocket::ClearSessionCache();
8136
8137 {
8138 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198139 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368140 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448141
[email protected]f7022f32014-08-21 16:32:198142 r->Start();
8143 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448144
[email protected]255620da2013-08-19 13:14:298145 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448146
8147 EXPECT_EQ(1, d.response_started_count());
8148 }
8149
8150 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8151 HttpNetworkSession::Params params;
8152 params.host_resolver = default_context_.host_resolver();
8153 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118154 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:448155 params.proxy_service = default_context_.proxy_service();
8156 params.ssl_config_service = default_context_.ssl_config_service();
8157 params.http_auth_handler_factory =
8158 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:418159 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:448160 params.http_server_properties = default_context_.http_server_properties();
8161 params.ssl_session_cache_shard = "alternate";
8162
mmenkee65e7af2015-10-13 17:16:428163 HttpNetworkSession network_session(params);
[email protected]cba24642014-08-15 20:49:598164 scoped_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428165 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448166
8167 default_context_.set_http_transaction_factory(cache.get());
8168
8169 {
8170 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198171 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368172 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448173
[email protected]f7022f32014-08-21 16:32:198174 r->Start();
8175 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448176
[email protected]255620da2013-08-19 13:14:298177 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448178
8179 // The response will look like;
8180 // insert abc
8181 // insert xyz
8182 //
8183 // With a newline at the end which makes the split think that there are
8184 // three lines.
8185
8186 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008187 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448188 }
8189}
8190
davidben8ecc3072014-09-03 23:19:098191#if defined(OS_WIN)
8192
8193namespace {
8194
8195bool IsECDSACipherSuite(uint16_t cipher_suite) {
8196 const char* key_exchange;
8197 const char* cipher;
8198 const char* mac;
8199 bool is_aead;
8200 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
8201 return std::string(key_exchange).find("ECDSA") != std::string::npos;
8202}
8203
8204} // namespace
8205
8206// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
8207// verified.
davidben9399c952014-10-07 04:09:118208TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:098209 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
8210 LOG(INFO) << "Skipping test on this version.";
8211 return;
8212 }
8213
8214 SpawnedTestServer test_server(
8215 SpawnedTestServer::TYPE_HTTPS,
8216 SpawnedTestServer::kLocalhost,
8217 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8218 ASSERT_TRUE(test_server.Start());
8219
8220 TestDelegate d;
8221 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368222 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:098223 r->Start();
8224 EXPECT_TRUE(r->is_pending());
8225
8226 base::RunLoop().Run();
8227
8228 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298229 std::vector<std::string> lines = base::SplitString(
8230 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
davidben8ecc3072014-09-03 23:19:098231
8232 for (size_t i = 0; i < lines.size(); i++) {
8233 int cipher_suite;
8234 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
8235 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
8236 << "ClientHello advertised " << cipher_suite;
8237 }
8238}
8239
8240#endif // OS_WIN
8241
Adam Langley32352ad2014-10-14 22:31:008242class TestSSLConfigService : public SSLConfigService {
8243 public:
8244 TestSSLConfigService(bool ev_enabled,
8245 bool online_rev_checking,
8246 bool rev_checking_required_local_anchors)
8247 : ev_enabled_(ev_enabled),
8248 online_rev_checking_(online_rev_checking),
8249 rev_checking_required_local_anchors_(
8250 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:028251 min_version_(kDefaultSSLVersionMin),
8252 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
8253
8254 void set_min_version(uint16 version) {
8255 min_version_ = version;
8256 }
Adam Langley32352ad2014-10-14 22:31:008257
8258 void set_fallback_min_version(uint16 version) {
8259 fallback_min_version_ = version;
8260 }
8261
8262 // SSLConfigService:
dchengb03027d2014-10-21 12:00:208263 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:008264 *config = SSLConfig();
8265 config->rev_checking_enabled = online_rev_checking_;
8266 config->verify_ev_cert = ev_enabled_;
8267 config->rev_checking_required_local_anchors =
8268 rev_checking_required_local_anchors_;
8269 if (fallback_min_version_) {
8270 config->version_fallback_min = fallback_min_version_;
8271 }
Adam Langleyac6f24b42014-10-31 20:24:028272 if (min_version_) {
8273 config->version_min = min_version_;
8274 }
Adam Langley32352ad2014-10-14 22:31:008275 }
8276
8277 protected:
dchengb03027d2014-10-21 12:00:208278 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:008279
8280 private:
8281 const bool ev_enabled_;
8282 const bool online_rev_checking_;
8283 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:028284 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:008285 uint16 fallback_min_version_;
8286};
8287
8288class FallbackTestURLRequestContext : public TestURLRequestContext {
8289 public:
8290 explicit FallbackTestURLRequestContext(bool delay_initialization)
8291 : TestURLRequestContext(delay_initialization) {}
8292
8293 void set_fallback_min_version(uint16 version) {
8294 TestSSLConfigService *ssl_config_service =
8295 new TestSSLConfigService(true /* check for EV */,
8296 false /* online revocation checking */,
8297 false /* require rev. checking for local
8298 anchors */);
8299 ssl_config_service->set_fallback_min_version(version);
8300 set_ssl_config_service(ssl_config_service);
8301 }
8302};
8303
[email protected]48d2b7c52014-06-27 01:16:558304class HTTPSFallbackTest : public testing::Test {
8305 public:
Adam Langley32352ad2014-10-14 22:31:008306 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298307 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558308
8309 protected:
8310 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8311 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008312 context_.Init();
8313 delegate_.set_allow_certificate_errors(true);
8314
[email protected]48d2b7c52014-06-27 01:16:558315 SpawnedTestServer test_server(
8316 SpawnedTestServer::TYPE_HTTPS,
8317 ssl_options,
8318 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8319 ASSERT_TRUE(test_server.Start());
8320
davidben151423e2015-03-23 18:48:368321 request_ = context_.CreateRequest(test_server.GetURL(std::string()),
8322 DEFAULT_PRIORITY, &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558323 request_->Start();
8324
8325 base::RunLoop().Run();
8326 }
8327
Adam Langley32352ad2014-10-14 22:31:008328 void set_fallback_min_version(uint16 version) {
8329 context_.set_fallback_min_version(version);
8330 }
8331
[email protected]48d2b7c52014-06-27 01:16:558332 void ExpectConnection(int version) {
8333 EXPECT_EQ(1, delegate_.response_started_count());
8334 EXPECT_NE(0, delegate_.bytes_received());
8335 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8336 request_->ssl_info().connection_status));
8337 EXPECT_TRUE(request_->ssl_info().connection_status &
8338 SSL_CONNECTION_VERSION_FALLBACK);
8339 }
8340
8341 void ExpectFailure(int error) {
8342 EXPECT_EQ(1, delegate_.response_started_count());
8343 EXPECT_FALSE(request_->status().is_success());
8344 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8345 EXPECT_EQ(error, request_->status().error());
8346 }
8347
8348 private:
8349 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008350 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558351 scoped_ptr<URLRequest> request_;
8352};
8353
davidbenb127ca82015-06-15 19:05:428354// Tests the TLS 1.0 fallback doesn't happen.
8355TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558356 SpawnedTestServer::SSLOptions ssl_options(
8357 SpawnedTestServer::SSLOptions::CERT_OK);
8358 ssl_options.tls_intolerant =
8359 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8360
8361 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428362 ExpectFailure(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION);
8363}
8364
8365// Tests the TLS 1.1 fallback.
8366TEST_F(HTTPSFallbackTest, TLSv1_1Fallback) {
davidbenb127ca82015-06-15 19:05:428367 SpawnedTestServer::SSLOptions ssl_options(
8368 SpawnedTestServer::SSLOptions::CERT_OK);
8369 ssl_options.tls_intolerant =
8370 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8371
8372 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8373 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
8374}
8375
8376// Tests that the TLS 1.1 fallback triggers on closed connections.
8377TEST_F(HTTPSFallbackTest, TLSv1_1FallbackClosed) {
davidbenb127ca82015-06-15 19:05:428378 SpawnedTestServer::SSLOptions ssl_options(
8379 SpawnedTestServer::SSLOptions::CERT_OK);
8380 ssl_options.tls_intolerant =
8381 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8382 ssl_options.tls_intolerance_type =
8383 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8384
8385 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8386 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558387}
8388
8389// This test is disabled on Android because the remote test server doesn't cause
8390// a TCP reset.
8391#if !defined(OS_ANDROID)
davidbenb127ca82015-06-15 19:05:428392// Tests fallback to TLS 1.1 on connection reset.
8393TEST_F(HTTPSFallbackTest, TLSv1_1FallbackReset) {
[email protected]48d2b7c52014-06-27 01:16:558394 SpawnedTestServer::SSLOptions ssl_options(
8395 SpawnedTestServer::SSLOptions::CERT_OK);
8396 ssl_options.tls_intolerant =
davidbenb127ca82015-06-15 19:05:428397 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
[email protected]48d2b7c52014-06-27 01:16:558398 ssl_options.tls_intolerance_type =
8399 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8400
8401 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428402 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558403}
8404#endif // !OS_ANDROID
8405
[email protected]12833302014-07-02 01:57:318406// Tests that we don't fallback on handshake failure with servers that implement
8407// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558408TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558409 SpawnedTestServer::SSLOptions ssl_options(
8410 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438411 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558412 // a version fallback.
8413 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438414 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558415 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8416 // connections are rejected.
8417 ssl_options.fallback_scsv_enabled = true;
8418
8419 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8420
8421 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8422 // intolerance. If the fallback SCSV is processed when the original error
8423 // that caused the fallback should be returned, which should be
8424 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8425 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8426}
8427
[email protected]12833302014-07-02 01:57:318428// Tests that we don't fallback on connection closed with servers that implement
8429// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318430TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318431 SpawnedTestServer::SSLOptions ssl_options(
8432 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438433 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318434 // a version fallback.
8435 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438436 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318437 ssl_options.tls_intolerance_type =
8438 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8439 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8440 // connections are rejected.
8441 ssl_options.fallback_scsv_enabled = true;
8442
8443 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8444
8445 // The original error should be replayed on rejected fallback.
8446 ExpectFailure(ERR_CONNECTION_CLOSED);
8447}
8448
davidbenb937d6c2015-05-14 04:53:428449// Test that fallback probe connections don't cause sessions to be cached.
8450TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008451 SpawnedTestServer::SSLOptions ssl_options(
8452 SpawnedTestServer::SSLOptions::CERT_OK);
8453 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428454 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008455 ssl_options.tls_intolerance_type =
8456 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8457 ssl_options.record_resume = true;
8458
8459 SpawnedTestServer test_server(
8460 SpawnedTestServer::TYPE_HTTPS,
8461 ssl_options,
8462 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8463 ASSERT_TRUE(test_server.Start());
8464
8465 SSLClientSocket::ClearSessionCache();
8466
davidbenb937d6c2015-05-14 04:53:428467 // Make a connection that does a probe fallback to TLSv1 but fails because
8468 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008469 // be inserted locally.
8470 {
8471 TestDelegate delegate;
8472 FallbackTestURLRequestContext context(true);
8473
davidbenb937d6c2015-05-14 04:53:428474 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008475 context.Init();
8476 scoped_ptr<URLRequest> request(context.CreateRequest(
davidben151423e2015-03-23 18:48:368477 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008478 request->Start();
8479
8480 base::RunLoop().Run();
8481
8482 EXPECT_EQ(1, delegate.response_started_count());
8483 EXPECT_FALSE(request->status().is_success());
8484 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8485 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8486 request->status().error());
8487 }
8488
davidbenb937d6c2015-05-14 04:53:428489 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008490 {
8491 TestDelegate delegate;
8492 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428493 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008494
8495 context.Init();
davidben151423e2015-03-23 18:48:368496 scoped_ptr<URLRequest> request(context.CreateRequest(
8497 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008498 request->Start();
8499
8500 base::RunLoop().Run();
8501
8502 EXPECT_EQ(1, delegate.response_started_count());
8503 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428504 EXPECT_EQ(
8505 SSL_CONNECTION_VERSION_TLS1,
8506 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008507 EXPECT_TRUE(request->ssl_info().connection_status &
8508 SSL_CONNECTION_VERSION_FALLBACK);
8509
8510 std::vector<std::string> lines;
8511 // If no sessions were cached then the server should have seen two sessions
8512 // inserted with no lookups.
8513 AssertTwoDistinctSessionsInserted(delegate.data_received());
8514 }
8515}
8516
[email protected]a8fed1742013-12-27 02:14:248517class HTTPSSessionTest : public testing::Test {
8518 public:
8519 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598520 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248521
8522 default_context_.set_network_delegate(&default_network_delegate_);
8523 default_context_.set_cert_verifier(&cert_verifier_);
8524 default_context_.Init();
8525 }
dcheng67be2b1f2014-10-27 21:47:298526 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248527
8528 protected:
8529 MockCertVerifier cert_verifier_;
8530 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8531 TestURLRequestContext default_context_;
8532};
8533
8534// Tests that session resumption is not attempted if an invalid certificate
8535// is presented.
8536TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8537 SpawnedTestServer::SSLOptions ssl_options;
8538 ssl_options.record_resume = true;
8539 SpawnedTestServer test_server(
8540 SpawnedTestServer::TYPE_HTTPS,
8541 ssl_options,
8542 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8543 ASSERT_TRUE(test_server.Start());
8544
8545 SSLClientSocket::ClearSessionCache();
8546
8547 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598548 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248549 {
8550 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198551 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368552 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248553
[email protected]f7022f32014-08-21 16:32:198554 r->Start();
8555 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248556
8557 base::RunLoop().Run();
8558
8559 EXPECT_EQ(1, d.response_started_count());
8560 }
8561
8562 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8563 CloseAllConnections();
8564
8565 // Now change the certificate to be acceptable (so that the response is
8566 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598567 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248568 {
8569 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198570 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368571 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248572
[email protected]f7022f32014-08-21 16:32:198573 r->Start();
8574 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248575
8576 base::RunLoop().Run();
8577
8578 // The response will look like;
8579 // insert abc
8580 // insert xyz
8581 //
8582 // With a newline at the end which makes the split think that there are
8583 // three lines.
8584 //
8585 // If a session was presented (eg: a bug), then the response would look
8586 // like;
8587 // insert abc
8588 // lookup abc
8589 // insert xyz
8590
8591 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008592 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248593 }
8594}
8595
[email protected]dffe8242012-03-20 15:14:278596// This the fingerprint of the "Testing CA" certificate used by the testserver.
8597// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268598static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278599 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8600 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8601
[email protected]51523f52013-07-31 21:57:288602// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8603// testserver.
8604static const SHA256HashValue kOCSPTestCertSPKI = { {
8605 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8606 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8607 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8608 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8609} };
8610
[email protected]dffe8242012-03-20 15:14:278611// This is the policy OID contained in the certificates that testserver
8612// generates.
8613static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8614
8615class HTTPSOCSPTest : public HTTPSRequestTest {
8616 public:
8617 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098618 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088619 ev_test_policy_(
8620 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8621 kOCSPTestCertFingerprint,
8622 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028623 }
8624
dcheng67be2b1f2014-10-27 21:47:298625 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098626 SetupContext(&context_);
8627 context_.Init();
[email protected]dffe8242012-03-20 15:14:278628
[email protected]cba24642014-08-15 20:49:598629 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208630 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428631 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508632 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278633
davidben71f35ff2015-04-17 20:54:488634#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098635 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278636 EnsureNSSHttpIOInit();
8637#endif
8638 }
8639
[email protected]ce7d0cbc2013-05-03 18:57:228640 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278641 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538642 // We always overwrite out_cert_status.
8643 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228644 SpawnedTestServer test_server(
8645 SpawnedTestServer::TYPE_HTTPS,
8646 ssl_options,
8647 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278648 ASSERT_TRUE(test_server.Start());
8649
8650 TestDelegate d;
8651 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:198652 scoped_ptr<URLRequest> r(context_.CreateRequest(
davidben151423e2015-03-23 18:48:368653 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198654 r->Start();
[email protected]dffe8242012-03-20 15:14:278655
[email protected]255620da2013-08-19 13:14:298656 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278657
8658 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198659 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278660 }
8661
dcheng67be2b1f2014-10-27 21:47:298662 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488663#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278664 ShutdownNSSHttpIO();
8665#endif
8666 }
8667
[email protected]a13234c2012-03-20 21:45:028668 protected:
8669 // SetupContext configures the URLRequestContext that will be used for making
8670 // connetions to testserver. This can be overridden in test subclasses for
8671 // different behaviour.
8672 virtual void SetupContext(URLRequestContext* context) {
8673 context->set_ssl_config_service(
8674 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208675 true /* online revocation checking */,
8676 false /* require rev. checking for local
8677 anchors */));
[email protected]a13234c2012-03-20 21:45:028678 }
8679
[email protected]dffe8242012-03-20 15:14:278680 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098681 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088682 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278683};
8684
[email protected]a13234c2012-03-20 21:45:028685static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018686#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028687 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8688 // have that ability on other platforms.
8689 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8690#else
8691 return 0;
8692#endif
8693}
8694
[email protected]3a86a712013-07-30 07:16:208695// SystemSupportsHardFailRevocationChecking returns true iff the current
8696// operating system supports revocation checking and can distinguish between
8697// situations where a given certificate lacks any revocation information (eg:
8698// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8699// revocation information cannot be obtained (eg: the CRL was unreachable).
8700// If it does not, then tests which rely on 'hard fail' behaviour should be
8701// skipped.
8702static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:488703#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:208704 return true;
8705#else
8706 return false;
8707#endif
8708}
8709
[email protected]a13234c2012-03-20 21:45:028710// SystemUsesChromiumEVMetadata returns true iff the current operating system
8711// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8712// several tests are effected because our testing EV certificate won't be
8713// recognised as EV.
8714static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328715#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578716 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8717 return false;
[email protected]e1b2d732014-03-28 16:20:328718#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8719 // On OS X and Android, we use the system to tell us whether a certificate is
8720 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018721 return false;
8722#else
8723 return true;
8724#endif
8725}
8726
[email protected]b6f2de32012-08-17 04:35:088727static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008728#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578729 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8730 return false;
8731#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028732 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8733#elif defined(OS_ANDROID)
8734 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8735 return false;
8736#else
8737 return true;
8738#endif
8739}
8740
davidbend1fb2f12014-11-08 02:51:008741static bool SystemSupportsOCSPStapling() {
davidben74b12ef02015-07-17 16:47:178742#if defined(USE_NSS_CERTS) || defined(OS_IOS)
davidbend1fb2f12014-11-08 02:51:008743 return true;
8744#elif defined(OS_WIN)
8745 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8746#else
8747 return false;
8748#endif
8749}
8750
[email protected]dffe8242012-03-20 15:14:278751TEST_F(HTTPSOCSPTest, Valid) {
8752 if (!SystemSupportsOCSP()) {
8753 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8754 return;
8755 }
8756
[email protected]ce7d0cbc2013-05-03 18:57:228757 SpawnedTestServer::SSLOptions ssl_options(
8758 SpawnedTestServer::SSLOptions::CERT_AUTO);
8759 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278760
[email protected]924e9f92012-12-16 22:00:538761 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128762 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278763
8764 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8765
[email protected]a13234c2012-03-20 21:45:028766 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8767 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278768
8769 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8770}
8771
8772TEST_F(HTTPSOCSPTest, Revoked) {
8773 if (!SystemSupportsOCSP()) {
8774 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8775 return;
8776 }
8777
[email protected]ce7d0cbc2013-05-03 18:57:228778 SpawnedTestServer::SSLOptions ssl_options(
8779 SpawnedTestServer::SSLOptions::CERT_AUTO);
8780 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278781
8782 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128783 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278784
[email protected]a592c0432012-12-01 18:10:298785#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278786 // Doesn't pass on OS X yet for reasons that need to be investigated.
8787 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8788#endif
8789 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8790 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8791}
8792
8793TEST_F(HTTPSOCSPTest, Invalid) {
8794 if (!SystemSupportsOCSP()) {
8795 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8796 return;
8797 }
8798
[email protected]ce7d0cbc2013-05-03 18:57:228799 SpawnedTestServer::SSLOptions ssl_options(
8800 SpawnedTestServer::SSLOptions::CERT_AUTO);
8801 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:278802
[email protected]924e9f92012-12-16 22:00:538803 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128804 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278805
[email protected]a13234c2012-03-20 21:45:028806 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278807 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:278808
8809 // Without a positive OCSP response, we shouldn't show the EV status.
8810 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8811 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8812}
[email protected]a13234c2012-03-20 21:45:028813
davidbend1fb2f12014-11-08 02:51:008814TEST_F(HTTPSOCSPTest, ValidStapled) {
8815 if (!SystemSupportsOCSPStapling()) {
8816 LOG(WARNING)
8817 << "Skipping test because system doesn't support OCSP stapling";
8818 return;
8819 }
8820
8821 SpawnedTestServer::SSLOptions ssl_options(
8822 SpawnedTestServer::SSLOptions::CERT_AUTO);
8823 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8824 ssl_options.staple_ocsp_response = true;
8825 ssl_options.ocsp_server_unavailable = true;
8826
8827 CertStatus cert_status;
8828 DoConnection(ssl_options, &cert_status);
8829
8830 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8831
8832 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8833 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8834
8835 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8836}
8837
davidben6c3191b2014-11-21 22:38:048838// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:488839#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:048840#define MAYBE_RevokedStapled DISABLED_RevokedStapled
8841#else
8842#define MAYBE_RevokedStapled RevokedStapled
8843#endif
8844TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
davidbend1fb2f12014-11-08 02:51:008845 if (!SystemSupportsOCSPStapling()) {
8846 LOG(WARNING)
8847 << "Skipping test because system doesn't support OCSP stapling";
8848 return;
8849 }
8850
8851 SpawnedTestServer::SSLOptions ssl_options(
8852 SpawnedTestServer::SSLOptions::CERT_AUTO);
8853 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8854 ssl_options.staple_ocsp_response = true;
8855 ssl_options.ocsp_server_unavailable = true;
8856
8857 CertStatus cert_status;
8858 DoConnection(ssl_options, &cert_status);
8859
8860 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8861 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8862 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8863}
8864
[email protected]3a86a712013-07-30 07:16:208865class HTTPSHardFailTest : public HTTPSOCSPTest {
8866 protected:
dchengb03027d2014-10-21 12:00:208867 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:208868 context->set_ssl_config_service(
8869 new TestSSLConfigService(false /* check for EV */,
8870 false /* online revocation checking */,
8871 true /* require rev. checking for local
8872 anchors */));
8873 }
8874};
8875
[email protected]3a86a712013-07-30 07:16:208876TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8877 if (!SystemSupportsOCSP()) {
8878 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8879 return;
8880 }
8881
8882 if (!SystemSupportsHardFailRevocationChecking()) {
8883 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8884 << "revocation checking";
8885 return;
8886 }
8887
8888 SpawnedTestServer::SSLOptions ssl_options(
8889 SpawnedTestServer::SSLOptions::CERT_AUTO);
8890 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8891
8892 CertStatus cert_status;
8893 DoConnection(ssl_options, &cert_status);
8894
8895 EXPECT_EQ(CERT_STATUS_REVOKED,
8896 cert_status & CERT_STATUS_REVOKED);
8897
8898 // Without a positive OCSP response, we shouldn't show the EV status.
8899 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8900}
8901
[email protected]a13234c2012-03-20 21:45:028902class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8903 protected:
dchengb03027d2014-10-21 12:00:208904 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028905 context->set_ssl_config_service(
8906 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208907 false /* online revocation checking */,
8908 false /* require rev. checking for local
8909 anchors */));
[email protected]a13234c2012-03-20 21:45:028910 }
8911};
8912
8913TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8914 if (!SystemSupportsOCSP()) {
8915 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8916 return;
8917 }
8918
[email protected]ce7d0cbc2013-05-03 18:57:228919 SpawnedTestServer::SSLOptions ssl_options(
8920 SpawnedTestServer::SSLOptions::CERT_AUTO);
8921 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028922 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8923
[email protected]924e9f92012-12-16 22:00:538924 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128925 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028926
8927 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8928 cert_status & CERT_STATUS_ALL_ERRORS);
8929
8930 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088931 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8932 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028933}
8934
[email protected]be0fff62013-08-29 23:37:488935TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8936 if (!SystemSupportsOCSP()) {
8937 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8938 return;
8939 }
8940
8941 SpawnedTestServer::SSLOptions ssl_options(
8942 SpawnedTestServer::SSLOptions::CERT_AUTO);
8943 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8944 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8945
8946 CertStatus cert_status;
8947 DoConnection(ssl_options, &cert_status);
8948
8949 // Currently only works for Windows. When using NSS or OS X, it's not
8950 // possible to determine whether the check failed because of actual
8951 // revocation or because there was an OCSP failure.
8952#if defined(OS_WIN)
8953 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8954#else
8955 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8956#endif
8957
8958 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8959 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8960 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8961}
8962
[email protected]a13234c2012-03-20 21:45:028963TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8964 if (!SystemSupportsOCSP()) {
8965 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8966 return;
8967 }
8968
[email protected]ce7d0cbc2013-05-03 18:57:228969 SpawnedTestServer::SSLOptions ssl_options(
8970 SpawnedTestServer::SSLOptions::CERT_AUTO);
8971 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:028972 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8973
8974 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128975 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028976
8977 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8978
8979 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8980 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:088981 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8982 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028983}
8984
8985TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8986 if (!SystemSupportsOCSP()) {
8987 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8988 return;
8989 }
8990
[email protected]ce7d0cbc2013-05-03 18:57:228991 SpawnedTestServer::SSLOptions ssl_options(
8992 SpawnedTestServer::SSLOptions::CERT_AUTO);
8993 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028994 SSLConfigService::SetCRLSet(
8995 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8996
8997 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128998 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028999
9000 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9001 cert_status & CERT_STATUS_ALL_ERRORS);
9002
9003 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089004 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9005 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029006}
9007
[email protected]51523f52013-07-31 21:57:289008TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9009 if (!SystemSupportsOCSP()) {
9010 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9011 return;
9012 }
9013
9014 SpawnedTestServer::SSLOptions ssl_options(
9015 SpawnedTestServer::SSLOptions::CERT_AUTO);
9016 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9017 SSLConfigService::SetCRLSet(
9018 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9019 false, &kOCSPTestCertSPKI, "")));
9020
9021 CertStatus cert_status;
9022 DoConnection(ssl_options, &cert_status);
9023
9024 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9025 // revocation check for EV.
9026 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9027 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9028 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9029 EXPECT_FALSE(
9030 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9031}
9032
9033TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9034 if (!SystemSupportsOCSP()) {
9035 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9036 return;
9037 }
9038
[email protected]ce7d0cbc2013-05-03 18:57:229039 SpawnedTestServer::SSLOptions ssl_options(
9040 SpawnedTestServer::SSLOptions::CERT_AUTO);
9041 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029042 SSLConfigService::SetCRLSet(
9043 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9044
[email protected]51523f52013-07-31 21:57:289045 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129046 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029047
[email protected]51523f52013-07-31 21:57:289048 // Even with a fresh CRLSet, we should still do online revocation checks when
9049 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9050 // test.
9051 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9052 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029053
[email protected]51523f52013-07-31 21:57:289054 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029055 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289056 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029057}
9058
[email protected]b6f2de32012-08-17 04:35:089059TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9060 // Test that when EV verification is requested, but online revocation
9061 // checking is disabled, and the leaf certificate is not in fact EV, that
9062 // no revocation checking actually happens.
9063 if (!SystemSupportsOCSP()) {
9064 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9065 return;
9066 }
9067
9068 // Unmark the certificate's OID as EV, which should disable revocation
9069 // checking (as per the user preference)
9070 ev_test_policy_.reset();
9071
[email protected]ce7d0cbc2013-05-03 18:57:229072 SpawnedTestServer::SSLOptions ssl_options(
9073 SpawnedTestServer::SSLOptions::CERT_AUTO);
9074 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089075 SSLConfigService::SetCRLSet(
9076 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9077
9078 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129079 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:089080
9081 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9082
9083 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9084 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9085}
9086
[email protected]a13234c2012-03-20 21:45:029087class HTTPSCRLSetTest : public HTTPSOCSPTest {
9088 protected:
dchengb03027d2014-10-21 12:00:209089 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:029090 context->set_ssl_config_service(
9091 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:209092 false /* online revocation checking */,
9093 false /* require rev. checking for local
9094 anchors */));
[email protected]a13234c2012-03-20 21:45:029095 }
9096};
9097
9098TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229099 SpawnedTestServer::SSLOptions ssl_options(
9100 SpawnedTestServer::SSLOptions::CERT_AUTO);
9101 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029102 SSLConfigService::SetCRLSet(
9103 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9104
[email protected]924e9f92012-12-16 22:00:539105 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129106 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029107
9108 // If we're not trying EV verification then, even if the CRLSet has expired,
9109 // we don't fall back to online revocation checks.
9110 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9111 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9112 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9113}
[email protected]51523f52013-07-31 21:57:289114
9115TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309116#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289117 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9118 return;
9119#endif
9120
9121 SpawnedTestServer::SSLOptions ssl_options(
9122 SpawnedTestServer::SSLOptions::CERT_AUTO);
9123 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9124 ssl_options.cert_serial = 10;
9125 SSLConfigService::SetCRLSet(
9126 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9127 false, &kOCSPTestCertSPKI, "\x0a")));
9128
9129 CertStatus cert_status = 0;
9130 DoConnection(ssl_options, &cert_status);
9131
9132 // If the certificate is recorded as revoked in the CRLSet, that should be
9133 // reflected without online revocation checking.
9134 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9135 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9136 EXPECT_FALSE(
9137 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9138}
[email protected]316c1e5e2012-09-12 15:17:449139#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279140
mmenke9f2ec60c2015-06-01 20:59:479141#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9142// These tests aren't passing on Android. Either the RemoteTestServer isn't
9143// starting up successfully, or it can't access the test files.
9144// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319145class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119146 public:
[email protected]d9fca99a2012-02-24 16:16:209147 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:479148 : ftp_transaction_factory_(&host_resolver_),
9149 test_server_(SpawnedTestServer::TYPE_FTP,
9150 SpawnedTestServer::kLocalhost,
9151 base::FilePath(kTestFilePath)) {
9152 // Can't use |default_context_|'s HostResolver to set up the
9153 // FTPTransactionFactory because it hasn't been created yet.
9154 default_context_.set_host_resolver(&host_resolver_);
9155 }
9156
9157 // URLRequestTest interface:
9158 void SetUpFactory() override {
9159 // Add FTP support to the default URLRequestContext.
9160 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:209161 "ftp",
9162 make_scoped_ptr(new FtpProtocolHandler(&ftp_transaction_factory_)));
mmenke9f2ec60c2015-06-01 20:59:479163 }
9164
9165 std::string GetTestFileContents() {
9166 base::FilePath path;
9167 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9168 path = path.Append(kTestFilePath);
9169 path = path.AppendASCII(kFtpTestFile);
9170 std::string contents;
9171 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9172 return contents;
[email protected]95409e12010-08-17 20:07:119173 }
9174
[email protected]b89ca032009-08-31 21:41:319175 protected:
mmenke9f2ec60c2015-06-01 20:59:479176 MockHostResolver host_resolver_;
9177 FtpNetworkLayer ftp_transaction_factory_;
9178
[email protected]ce7d0cbc2013-05-03 18:57:229179 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:319180};
9181
[email protected]d2a133182012-08-05 16:44:089182// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099183TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089184 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089185
9186 TestDelegate d;
9187 {
davidben151423e2015-03-23 18:48:369188 scoped_ptr<URLRequest> r(
9189 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199190 r->Start();
9191 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089192
[email protected]255620da2013-08-19 13:14:299193 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089194
[email protected]f7022f32014-08-21 16:32:199195 EXPECT_FALSE(r->is_pending());
9196 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
9197 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:089198 }
9199}
9200
mmenke9f2ec60c2015-06-01 20:59:479201TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:119202 ASSERT_TRUE(test_server_.Start());
9203
[email protected]a25e90e2009-09-09 17:05:379204 TestDelegate d;
9205 {
[email protected]f7022f32014-08-21 16:32:199206 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369207 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199208 r->Start();
9209 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379210
[email protected]255620da2013-08-19 13:14:299211 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379212
[email protected]f7022f32014-08-21 16:32:199213 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379214 EXPECT_EQ(1, d.response_started_count());
9215 EXPECT_FALSE(d.received_data_before_response());
9216 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:199217 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199218 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199219 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199220 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379221 }
9222}
9223
mmenke9f2ec60c2015-06-01 20:59:479224TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:119225 ASSERT_TRUE(test_server_.Start());
9226
[email protected]dd265012009-01-08 20:45:279227 TestDelegate d;
9228 {
[email protected]f7022f32014-08-21 16:32:199229 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479230 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199231 r->Start();
9232 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279233
[email protected]255620da2013-08-19 13:14:299234 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279235
[email protected]f7022f32014-08-21 16:32:199236 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279237 EXPECT_EQ(1, d.response_started_count());
9238 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479239 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:199240 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199241 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199242 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199243 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279244 }
9245}
9246
mmenke9f2ec60c2015-06-01 20:59:479247TEST_F(URLRequestTestFTP, FTPGetTest) {
[email protected]95409e12010-08-17 20:07:119248 ASSERT_TRUE(test_server_.Start());
9249
[email protected]dd265012009-01-08 20:45:279250 TestDelegate d;
9251 {
mmenke9f2ec60c2015-06-01 20:59:479252 scoped_ptr<URLRequest> r(
9253 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9254 kFtpTestFile, "chrome", "chrome"),
9255 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199256 r->Start();
9257 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279258
[email protected]255620da2013-08-19 13:14:299259 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279260
[email protected]f7022f32014-08-21 16:32:199261 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479262 EXPECT_EQ(1, d.response_started_count());
9263 EXPECT_FALSE(d.received_data_before_response());
9264 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:199265 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199266 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199267 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199268 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:259269
9270 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:199271 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:259272 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:279273 }
9274}
9275
mmenke9f2ec60c2015-06-01 20:59:479276TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:119277 ASSERT_TRUE(test_server_.Start());
9278
[email protected]dd265012009-01-08 20:45:279279 TestDelegate d;
9280 {
[email protected]f7022f32014-08-21 16:32:199281 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479282 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199283 "wrong_password"),
davidben151423e2015-03-23 18:48:369284 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199285 r->Start();
9286 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279287
[email protected]255620da2013-08-19 13:14:299288 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279289
[email protected]f7022f32014-08-21 16:32:199290 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279291 EXPECT_EQ(1, d.response_started_count());
9292 EXPECT_FALSE(d.received_data_before_response());
9293 EXPECT_EQ(d.bytes_received(), 0);
9294 }
9295}
9296
mmenke9f2ec60c2015-06-01 20:59:479297TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:119298 ASSERT_TRUE(test_server_.Start());
9299
[email protected]8b8a197d2009-08-26 15:57:589300 TestDelegate d;
9301 // Set correct login credentials. The delegate will be asked for them when
9302 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589303 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589304 {
[email protected]f7022f32014-08-21 16:32:199305 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479306 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199307 "wrong_password"),
davidben151423e2015-03-23 18:48:369308 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199309 r->Start();
9310 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589311
[email protected]255620da2013-08-19 13:14:299312 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589313
[email protected]f7022f32014-08-21 16:32:199314 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589315 EXPECT_EQ(1, d.response_started_count());
9316 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479317 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589318 }
9319}
9320
mmenke9f2ec60c2015-06-01 20:59:479321TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:119322 ASSERT_TRUE(test_server_.Start());
9323
[email protected]dd265012009-01-08 20:45:279324 TestDelegate d;
9325 {
mmenke9f2ec60c2015-06-01 20:59:479326 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9327 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9328 "chrome"),
9329 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199330 r->Start();
9331 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279332
[email protected]255620da2013-08-19 13:14:299333 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279334
[email protected]f7022f32014-08-21 16:32:199335 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279336 EXPECT_EQ(1, d.response_started_count());
9337 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479338 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279339 }
9340}
[email protected]8b8a197d2009-08-26 15:57:589341
mmenke9f2ec60c2015-06-01 20:59:479342TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:119343 ASSERT_TRUE(test_server_.Start());
9344
[email protected]8b8a197d2009-08-26 15:57:589345 TestDelegate d;
9346 // Set correct login credentials. The delegate will be asked for them when
9347 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589348 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589349 {
mmenke9f2ec60c2015-06-01 20:59:479350 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9351 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9352 "chrome"),
9353 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199354 r->Start();
9355 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589356
[email protected]255620da2013-08-19 13:14:299357 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589358
[email protected]f7022f32014-08-21 16:32:199359 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589360 EXPECT_EQ(1, d.response_started_count());
9361 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479362 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589363 }
9364}
[email protected]60a3df52009-09-22 16:13:249365
mmenke9f2ec60c2015-06-01 20:59:479366TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:119367 ASSERT_TRUE(test_server_.Start());
9368
[email protected]60a3df52009-09-22 16:13:249369 scoped_ptr<TestDelegate> d(new TestDelegate);
9370 {
9371 // Pass correct login identity in the URL.
mmenke9f2ec60c2015-06-01 20:59:479372 scoped_ptr<URLRequest> r(
9373 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9374 kFtpTestFile, "chrome", "chrome"),
9375 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199376 r->Start();
9377 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249378
[email protected]255620da2013-08-19 13:14:299379 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249380
[email protected]f7022f32014-08-21 16:32:199381 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249382 EXPECT_EQ(1, d->response_started_count());
9383 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479384 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249385 }
9386
9387 d.reset(new TestDelegate);
9388 {
9389 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199390 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479391 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199392 r->Start();
9393 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249394
[email protected]255620da2013-08-19 13:14:299395 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249396
[email protected]f7022f32014-08-21 16:32:199397 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249398 EXPECT_EQ(1, d->response_started_count());
9399 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479400 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249401 }
9402}
9403
mmenke9f2ec60c2015-06-01 20:59:479404TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:119405 ASSERT_TRUE(test_server_.Start());
9406
[email protected]60a3df52009-09-22 16:13:249407 scoped_ptr<TestDelegate> d(new TestDelegate);
9408 // Set correct login credentials. The delegate will be asked for them when
9409 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589410 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249411 {
[email protected]f7022f32014-08-21 16:32:199412 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479413 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199414 "wrong_password"),
davidben151423e2015-03-23 18:48:369415 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199416 r->Start();
9417 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249418
[email protected]255620da2013-08-19 13:14:299419 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249420
[email protected]f7022f32014-08-21 16:32:199421 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249422 EXPECT_EQ(1, d->response_started_count());
9423 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479424 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249425 }
9426
9427 // Use a new delegate without explicit credentials. The cached ones should be
9428 // used.
9429 d.reset(new TestDelegate);
9430 {
9431 // Don't pass wrong credentials in the URL, they would override valid cached
9432 // ones.
[email protected]f7022f32014-08-21 16:32:199433 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479434 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199435 r->Start();
9436 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249437
[email protected]255620da2013-08-19 13:14:299438 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249439
[email protected]f7022f32014-08-21 16:32:199440 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249441 EXPECT_EQ(1, d->response_started_count());
9442 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479443 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249444 }
9445}
[email protected]316c1e5e2012-09-12 15:17:449446#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519447
ttuttlec0c828492015-05-15 01:25:559448TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9449 TestDelegate d;
9450 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9451 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9452 d.set_quit_on_network_start(true);
9453
9454 EXPECT_FALSE(req->response_info().network_accessed);
9455
9456 req->Start();
9457 base::RunLoop().Run();
9458
9459 EXPECT_EQ(1, d.received_before_network_start_count());
9460 EXPECT_EQ(0, d.response_started_count());
9461 EXPECT_FALSE(req->response_info().network_accessed);
9462
9463 req->ResumeNetworkStart();
9464 base::RunLoop().Run();
9465}
9466
9467TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9468 TestDelegate d;
9469 scoped_ptr<URLRequest> req(
9470 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9471
9472 EXPECT_FALSE(req->response_info().network_accessed);
9473
9474 req->Start();
9475 base::RunLoop().Run();
9476
9477 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9478 EXPECT_FALSE(req->response_info().network_accessed);
9479}
9480
9481TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9482 MockHostResolver host_resolver;
9483 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9484 TestURLRequestContext context(true);
9485 context.set_network_delegate(&network_delegate);
9486 context.set_host_resolver(&host_resolver);
9487 host_resolver.rules()->AddSimulatedFailure("*");
9488 context.Init();
9489
9490 TestDelegate d;
9491 scoped_ptr<URLRequest> req(context.CreateRequest(
9492 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9493
9494 EXPECT_FALSE(req->response_info().network_accessed);
9495
9496 req->Start();
9497 base::RunLoop().Run();
9498 EXPECT_TRUE(req->response_info().network_accessed);
9499}
9500
alexanderkcd904b52015-07-24 18:57:229501// Test that URLRequest is canceled correctly and with detached request
9502// URLRequestRedirectJob does not crash in StartAsync.
9503// See http://crbug.com/508900
9504TEST_F(URLRequestTest, URLRequestRedirectJobDetachRequestNoCrash) {
9505 TestDelegate d;
9506 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9507 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
9508
9509 URLRequestRedirectJob* job = new URLRequestRedirectJob(
9510 req.get(), &default_network_delegate_,
9511 GURL("http://this-should-never-be-navigated-to/"),
9512 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp");
9513 AddTestInterceptor()->set_main_intercept_job(job);
9514
9515 req->Start();
9516 req->Cancel();
9517 job->DetachRequest();
9518 base::RunLoop().RunUntilIdle();
9519 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
9520 EXPECT_EQ(0, d.received_redirect_count());
9521}
9522
[email protected]7461a402011-03-24 23:19:519523} // namespace net