blob: cf34139e904cbe97509204e4a4a13196480cfb4e [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>
avibf0746c2015-12-09 19:53:1415#include <limits>
initial.commit586acc5fe2008-07-26 22:42:5216
[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"
tommycli59a63432015-11-06 00:10:5580#include "net/ssl/ssl_server_config.h"
[email protected]6e7845ae2013-03-29 21:48:1181#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:3682#include "net/test/embedded_test_server/embedded_test_server.h"
83#include "net/test/embedded_test_server/http_request.h"
84#include "net/test/embedded_test_server/http_response.h"
[email protected]89b32522013-05-07 20:04:2185#include "net/test/spawned_test_server/spawned_test_server.h"
mmenkefb18c772015-09-30 22:22:5086#include "net/test/url_request/url_request_failed_job.h"
[email protected]e0f35c92013-05-08 16:04:3487#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4388#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5289#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:5090#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:1491#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:5092#include "net/url_request/url_request_intercepting_job_factory.h"
93#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:4994#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5195#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4796#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4497#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5298#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1599#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52100
[email protected]02494ec2014-05-07 15:05:29101#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55102#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29103#include "net/url_request/file_protocol_handler.h"
104#include "net/url_request/url_request_file_dir_job.h"
105#endif
106
mmenke9f2ec60c2015-06-01 20:59:47107#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
108#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29109#include "net/url_request/ftp_protocol_handler.h"
110#endif
111
[email protected]dffe8242012-03-20 15:14:27112#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48113#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56114#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27115#include "base/win/windows_version.h"
116#endif
117
[email protected]ad65a3e2013-12-25 18:18:01118using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33119using base::Time;
halton.huoe4e45742014-12-08 07:55:46120using std::string;
[email protected]e1acf6f2008-10-27 20:43:33121
[email protected]7461a402011-03-24 23:19:51122namespace net {
123
initial.commit586acc5fe2008-07-26 22:42:52124namespace {
125
[email protected]42cba2fb2013-03-29 19:58:57126const base::string16 kChrome(ASCIIToUTF16("chrome"));
127const base::string16 kSecret(ASCIIToUTF16("secret"));
128const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44129
mmenke9f2ec60c2015-06-01 20:59:47130const base::FilePath::CharType kTestFilePath[] =
131 FILE_PATH_LITERAL("net/data/url_request_unittest");
132
133#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
134// Test file used in most FTP tests.
135const char kFtpTestFile[] = "BullRunSpeech.txt";
136#endif
137
[email protected]2bba3252013-04-08 19:50:59138// Tests load timing information in the case a fresh connection was used, with
139// no proxy.
[email protected]cba24642014-08-15 20:49:59140void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25141 int connect_timing_flags) {
142 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59143 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25144
145 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
146 EXPECT_FALSE(load_timing_info.request_start.is_null());
147
148 EXPECT_LE(load_timing_info.request_start,
149 load_timing_info.connect_timing.connect_start);
150 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
151 connect_timing_flags);
152 EXPECT_LE(load_timing_info.connect_timing.connect_end,
153 load_timing_info.send_start);
154 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
155 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
156
[email protected]58e32bb2013-01-21 18:23:25157 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
158 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
159}
160
[email protected]2bba3252013-04-08 19:50:59161// Same as above, but with proxy times.
162void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59163 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59164 int connect_timing_flags) {
165 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59166 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59167
168 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
169 EXPECT_FALSE(load_timing_info.request_start.is_null());
170
171 EXPECT_LE(load_timing_info.request_start,
172 load_timing_info.proxy_resolve_start);
173 EXPECT_LE(load_timing_info.proxy_resolve_start,
174 load_timing_info.proxy_resolve_end);
175 EXPECT_LE(load_timing_info.proxy_resolve_end,
176 load_timing_info.connect_timing.connect_start);
177 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
178 connect_timing_flags);
179 EXPECT_LE(load_timing_info.connect_timing.connect_end,
180 load_timing_info.send_start);
181 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
182 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
183}
184
185// Same as above, but with a reused socket and proxy times.
186void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59187 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59188 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59189 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59190
191 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
192 EXPECT_FALSE(load_timing_info.request_start.is_null());
193
194 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
195
196 EXPECT_LE(load_timing_info.request_start,
197 load_timing_info.proxy_resolve_start);
198 EXPECT_LE(load_timing_info.proxy_resolve_start,
199 load_timing_info.proxy_resolve_end);
200 EXPECT_LE(load_timing_info.proxy_resolve_end,
201 load_timing_info.send_start);
202 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
203 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
204}
205
xunjielia6888202015-04-14 21:34:25206#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25207// Tests load timing information in the case of a cache hit, when no cache
208// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17209base::StringPiece TestNetResourceProvider(int key) {
210 return "header";
211}
212
213void FillBuffer(char* buffer, size_t len) {
214 static bool called = false;
215 if (!called) {
216 called = true;
217 int seed = static_cast<int>(Time::Now().ToInternalValue());
218 srand(seed);
219 }
220
221 for (size_t i = 0; i < len; i++) {
222 buffer[i] = static_cast<char>(rand());
223 if (!buffer[i])
224 buffer[i] = 'g';
225 }
226}
xunjielia6888202015-04-14 21:34:25227#endif
[email protected]e3a85452013-11-14 01:46:17228
[email protected]3b23a222013-05-15 21:33:25229void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59230 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25231 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59232 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25233
234 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
235 EXPECT_FALSE(load_timing_info.request_start.is_null());
236
237 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
238 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
239 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
240 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
241
242 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
243 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
244}
245
mmenke9f2ec60c2015-06-01 20:59:47246#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25247// Tests load timing in the case that there is no HTTP response. This can be
248// used to test in the case of errors or non-HTTP requests.
249void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59250 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25251 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59252 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25253
254 // Only the request times should be non-null.
255 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
256 EXPECT_FALSE(load_timing_info.request_start.is_null());
257
258 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
259
260 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
261 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
262 EXPECT_TRUE(load_timing_info.send_start.is_null());
263 EXPECT_TRUE(load_timing_info.send_end.is_null());
264 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
265}
xunjielia6888202015-04-14 21:34:25266#endif
[email protected]58e32bb2013-01-21 18:23:25267
mmenkefb18c772015-09-30 22:22:50268// Test power monitor source that can simulate entering suspend mode. Can't use
269// the one in base/ because it insists on bringing its own MessageLoop.
270class TestPowerMonitorSource : public base::PowerMonitorSource {
271 public:
272 TestPowerMonitorSource() {}
273 ~TestPowerMonitorSource() override {}
274
275 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
276
277 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
278
279 bool IsOnBatteryPowerImpl() override { return false; }
280
281 private:
282 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
283};
284
mmenkeed0498b2015-12-08 23:20:42285// Job that allows monitoring of its priority.
286class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
287 public:
288 // The latest priority of the job is always written to |request_priority_|.
289 PriorityMonitoringURLRequestJob(URLRequest* request,
290 NetworkDelegate* network_delegate,
291 RequestPriority* request_priority)
292 : URLRequestTestJob(request, network_delegate),
293 request_priority_(request_priority) {
294 *request_priority_ = DEFAULT_PRIORITY;
295 }
296
297 void SetPriority(RequestPriority priority) override {
298 *request_priority_ = priority;
299 URLRequestTestJob::SetPriority(priority);
300 }
301
302 private:
303 RequestPriority* const request_priority_;
304};
305
[email protected]71c64f62008-11-15 04:36:51306// Do a case-insensitive search through |haystack| for |needle|.
307bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50308 std::string::const_iterator it = std::search(
309 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
310 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51311 return it != haystack.end();
312}
313
mmenkecbc2b712014-10-09 20:29:07314scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
[email protected]f288ef02012-12-15 20:28:28315 scoped_ptr<UploadElementReader> reader(
316 new UploadBytesElementReader(data, strlen(data)));
mmenkecbc2b712014-10-09 20:29:07317 return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23318}
319
[email protected]96adadb2010-08-28 01:16:17320// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51321void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17322 // -1 means unknown. 0 means no encryption.
323 EXPECT_GT(ssl_info.security_bits, 0);
324
325 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14326 uint16_t cipher_suite =
327 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29328 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17329}
330
[email protected]79e1fd62013-06-20 06:50:04331void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
332 const GURL& host_url) {
333 std::string sent_value;
334
335 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
336 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
337
338 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
339 EXPECT_EQ("keep-alive", sent_value);
340}
341
tommycli59a63432015-11-06 00:10:55342#if !defined(OS_IOS)
[email protected]ede03212012-09-07 12:52:26343bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27344 size_t size = a.size();
345
346 if (size != b.size())
347 return false;
348
349 for (size_t i = 0; i < size; ++i) {
350 if (!a[i].Equals(b[i]))
351 return false;
352 }
353
354 return true;
355}
[email protected]e3a85452013-11-14 01:46:17356#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27357
[email protected]dc5a5cf2012-09-26 02:49:30358// A network delegate that allows the user to choose a subset of request stages
359// to block in. When blocking, the delegate can do one of the following:
360// * synchronously return a pre-specified error code, or
361// * asynchronously return that value via an automatically called callback,
362// or
363// * block and wait for the user to do a callback.
364// Additionally, the user may also specify a redirect URL -- then each request
365// with the current URL different from the redirect target will be redirected
366// to that target, in the on-before-URL-request stage, independent of whether
367// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12368class BlockingNetworkDelegate : public TestNetworkDelegate {
369 public:
[email protected]dc5a5cf2012-09-26 02:49:30370 // Stages in which the delegate can block.
371 enum Stage {
[email protected]9045b8822012-01-13 20:35:35372 NOT_BLOCKED = 0,
373 ON_BEFORE_URL_REQUEST = 1 << 0,
374 ON_BEFORE_SEND_HEADERS = 1 << 1,
375 ON_HEADERS_RECEIVED = 1 << 2,
376 ON_AUTH_REQUIRED = 1 << 3
377 };
378
[email protected]dc5a5cf2012-09-26 02:49:30379 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59380 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30381 enum BlockMode {
382 SYNCHRONOUS, // No callback, returns specified return values.
383 AUTO_CALLBACK, // |this| posts a task to run the callback using the
384 // specified return codes.
385 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
386 // |auth_retval_| are ignored. In every blocking stage the
387 // message loop is quit.
388 };
389
390 // Creates a delegate which does not block at all.
391 explicit BlockingNetworkDelegate(BlockMode block_mode);
392
393 // For users to trigger a callback returning |response|.
394 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
395 // Only call if |block_mode_| == USER_CALLBACK.
396 void DoCallback(int response);
397 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
398
399 // Setters.
400 void set_retval(int retval) {
401 ASSERT_NE(USER_CALLBACK, block_mode_);
402 ASSERT_NE(ERR_IO_PENDING, retval);
403 ASSERT_NE(OK, retval);
404 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35405 }
406
[email protected]dc5a5cf2012-09-26 02:49:30407 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
408 // |auth_credentials_| will be passed with the response.
409 void set_auth_retval(AuthRequiredResponse auth_retval) {
410 ASSERT_NE(USER_CALLBACK, block_mode_);
411 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
412 auth_retval_ = auth_retval;
413 }
414 void set_auth_credentials(const AuthCredentials& auth_credentials) {
415 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35416 }
417
[email protected]dc5a5cf2012-09-26 02:49:30418 void set_redirect_url(const GURL& url) {
419 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35420 }
421
[email protected]dc5a5cf2012-09-26 02:49:30422 void set_block_on(int block_on) {
423 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35424 }
425
[email protected]dc5a5cf2012-09-26 02:49:30426 // Allows the user to check in which state did we block.
427 Stage stage_blocked_for_callback() const {
428 EXPECT_EQ(USER_CALLBACK, block_mode_);
429 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35430 }
431
432 private:
[email protected]dc5a5cf2012-09-26 02:49:30433 void RunCallback(int response, const CompletionCallback& callback);
434 void RunAuthCallback(AuthRequiredResponse response,
435 const AuthCallback& callback);
436
[email protected]9045b8822012-01-13 20:35:35437 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20438 int OnBeforeURLRequest(URLRequest* request,
439 const CompletionCallback& callback,
440 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35441
dchengb03027d2014-10-21 12:00:20442 int OnBeforeSendHeaders(URLRequest* request,
443 const CompletionCallback& callback,
444 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35445
dchengb03027d2014-10-21 12:00:20446 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35447 URLRequest* request,
448 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32449 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16450 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13451 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35452
dchengb03027d2014-10-21 12:00:20453 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35454 URLRequest* request,
455 const AuthChallengeInfo& auth_info,
456 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13457 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35458
[email protected]dc5a5cf2012-09-26 02:49:30459 // Resets the callbacks and |stage_blocked_for_callback_|.
460 void Reset();
[email protected]9045b8822012-01-13 20:35:35461
[email protected]dc5a5cf2012-09-26 02:49:30462 // Checks whether we should block in |stage|. If yes, returns an error code
463 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
464 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
465
466 // Configuration parameters, can be adjusted by public methods:
467 const BlockMode block_mode_;
468
469 // Values returned on blocking stages when mode is SYNCHRONOUS or
470 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
471 int retval_; // To be returned in non-auth stages.
472 AuthRequiredResponse auth_retval_;
473
[email protected]5f714132014-03-26 10:41:16474 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30475 int block_on_; // Bit mask: in which stages to block.
476
477 // |auth_credentials_| will be copied to |*target_auth_credential_| on
478 // callback.
479 AuthCredentials auth_credentials_;
480 AuthCredentials* target_auth_credentials_;
481
482 // Internal variables, not set by not the user:
483 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
484 // USER_CALLBACK).
485 Stage stage_blocked_for_callback_;
486
487 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35488 CompletionCallback callback_;
489 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30490
491 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
492
493 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35494};
495
[email protected]dc5a5cf2012-09-26 02:49:30496BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
497 : block_mode_(block_mode),
498 retval_(OK),
499 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
500 block_on_(0),
501 target_auth_credentials_(NULL),
502 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32503 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30504}
505
506void BlockingNetworkDelegate::DoCallback(int response) {
507 ASSERT_EQ(USER_CALLBACK, block_mode_);
508 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
509 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
510 CompletionCallback callback = callback_;
511 Reset();
512 RunCallback(response, callback);
513}
514
515void BlockingNetworkDelegate::DoAuthCallback(
516 NetworkDelegate::AuthRequiredResponse response) {
517 ASSERT_EQ(USER_CALLBACK, block_mode_);
518 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
519 AuthCallback auth_callback = auth_callback_;
520 Reset();
521 RunAuthCallback(response, auth_callback);
522}
523
524void BlockingNetworkDelegate::RunCallback(int response,
525 const CompletionCallback& callback) {
526 callback.Run(response);
527}
528
529void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
530 const AuthCallback& callback) {
531 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
532 ASSERT_TRUE(target_auth_credentials_ != NULL);
533 *target_auth_credentials_ = auth_credentials_;
534 }
535 callback.Run(response);
536}
537
538int BlockingNetworkDelegate::OnBeforeURLRequest(
539 URLRequest* request,
540 const CompletionCallback& callback,
541 GURL* new_url) {
542 if (redirect_url_ == request->url())
543 return OK; // We've already seen this request and redirected elsewhere.
544
545 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
546
547 if (!redirect_url_.is_empty())
548 *new_url = redirect_url_;
549
550 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
551}
552
553int BlockingNetworkDelegate::OnBeforeSendHeaders(
554 URLRequest* request,
555 const CompletionCallback& callback,
556 HttpRequestHeaders* headers) {
557 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
558
559 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
560}
561
562int BlockingNetworkDelegate::OnHeadersReceived(
563 URLRequest* request,
564 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32565 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16566 scoped_refptr<HttpResponseHeaders>* override_response_headers,
567 GURL* allowed_unsafe_redirect_url) {
568 TestNetworkDelegate::OnHeadersReceived(request,
569 callback,
570 original_response_headers,
571 override_response_headers,
572 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30573
574 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
575}
576
577NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
578 URLRequest* request,
579 const AuthChallengeInfo& auth_info,
580 const AuthCallback& callback,
581 AuthCredentials* credentials) {
582 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
583 credentials);
584 // Check that the user has provided callback for the previous blocked stage.
585 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
586
587 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
588 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
589 }
590
591 target_auth_credentials_ = credentials;
592
593 switch (block_mode_) {
594 case SYNCHRONOUS:
595 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
596 *target_auth_credentials_ = auth_credentials_;
597 return auth_retval_;
598
599 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45600 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30601 FROM_HERE,
602 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
603 weak_factory_.GetWeakPtr(), auth_retval_, callback));
604 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
605
606 case USER_CALLBACK:
607 auth_callback_ = callback;
608 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45609 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17610 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30611 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
612 }
613 NOTREACHED();
614 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
615}
616
617void BlockingNetworkDelegate::Reset() {
618 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
619 stage_blocked_for_callback_ = NOT_BLOCKED;
620 callback_.Reset();
621 auth_callback_.Reset();
622}
623
624int BlockingNetworkDelegate::MaybeBlockStage(
625 BlockingNetworkDelegate::Stage stage,
626 const CompletionCallback& callback) {
627 // Check that the user has provided callback for the previous blocked stage.
628 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
629
630 if ((block_on_ & stage) == 0) {
631 return OK;
632 }
633
634 switch (block_mode_) {
635 case SYNCHRONOUS:
636 EXPECT_NE(OK, retval_);
637 return retval_;
638
639 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45640 base::ThreadTaskRunnerHandle::Get()->PostTask(
641 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
642 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30643 return ERR_IO_PENDING;
644
645 case USER_CALLBACK:
646 callback_ = callback;
647 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45648 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17649 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30650 return ERR_IO_PENDING;
651 }
652 NOTREACHED();
653 return 0;
654}
655
[email protected]d5a4dd62012-05-23 01:41:04656class TestURLRequestContextWithProxy : public TestURLRequestContext {
657 public:
658 // Does not own |delegate|.
659 TestURLRequestContextWithProxy(const std::string& proxy,
660 NetworkDelegate* delegate)
661 : TestURLRequestContext(true) {
662 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
663 set_network_delegate(delegate);
664 Init();
665 }
dchengb03027d2014-10-21 12:00:20666 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04667};
668
estark06e0dac2015-08-07 21:56:01669// A mock ReportSender that just remembers the latest report
670// URI and report to be sent.
671class MockCertificateReportSender
672 : public TransportSecurityState::ReportSender {
673 public:
674 MockCertificateReportSender() {}
675 ~MockCertificateReportSender() override {}
676
677 void Send(const GURL& report_uri, const std::string& report) override {
678 latest_report_uri_ = report_uri;
679 latest_report_ = report;
680 }
681
682 const GURL& latest_report_uri() { return latest_report_uri_; }
683 const std::string& latest_report() { return latest_report_; }
684
685 private:
686 GURL latest_report_uri_;
687 std::string latest_report_;
688};
689
estarkcd39c11f2015-10-19 19:46:36690class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
691 public:
692 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
jww79aceda2015-12-07 01:56:34693 bool OnAreStrictSecureCookiesEnabled() const override { return true; }
estarkcd39c11f2015-10-19 19:46:36694};
695
[email protected]d5a4dd62012-05-23 01:41:04696} // namespace
697
[email protected]a592c0432012-12-01 18:10:29698// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48699class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00700 public:
[email protected]ef2bf422012-05-11 03:27:09701 URLRequestTest() : default_context_(true) {
702 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25703 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50704 job_factory_impl_ = new URLRequestJobFactoryImpl();
705 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50706 }
bengr1bf8e942014-11-07 01:36:50707
dcheng67be2b1f2014-10-27 21:47:29708 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18709 // URLRequestJobs may post clean-up tasks on destruction.
710 base::RunLoop().RunUntilIdle();
711 }
[email protected]87a09a92011-07-14 15:50:50712
dcheng2339883c2014-12-23 00:23:05713 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50714 SetUpFactory();
715 default_context_.set_job_factory(job_factory_.get());
716 default_context_.Init();
717 PlatformTest::SetUp();
718 }
719
720 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20721 job_factory_impl_->SetProtocolHandler(
722 "data", make_scoped_ptr(new DataProtocolHandler));
bengr1bf8e942014-11-07 01:36:50723#if !defined(DISABLE_FILE_SUPPORT)
724 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:20725 "file", make_scoped_ptr(new FileProtocolHandler(
726 base::ThreadTaskRunnerHandle::Get())));
bengr1bf8e942014-11-07 01:36:50727#endif
728 }
729
730 TestNetworkDelegate* default_network_delegate() {
731 return &default_network_delegate_;
732 }
733
734 const TestURLRequestContext& default_context() const {
735 return default_context_;
736 }
737
738
[email protected]3c5ca8c2011-09-29 01:14:51739 // Adds the TestJobInterceptor to the default context.
740 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23741 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20742 job_factory_impl_->SetProtocolHandler("http", nullptr);
743 job_factory_impl_->SetProtocolHandler("http",
744 make_scoped_ptr(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23745 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51746 }
747
[email protected]87a09a92011-07-14 15:50:50748 protected:
vishal.b62985ca92015-04-17 08:45:51749 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24750 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50751 URLRequestJobFactoryImpl* job_factory_impl_;
752 scoped_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09753 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48754};
755
[email protected]316c1e5e2012-09-12 15:17:44756TEST_F(URLRequestTest, AboutBlankTest) {
757 TestDelegate d;
758 {
[email protected]f7022f32014-08-21 16:32:19759 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36760 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44761
[email protected]f7022f32014-08-21 16:32:19762 r->Start();
763 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44764
[email protected]255620da2013-08-19 13:14:29765 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44766
[email protected]f7022f32014-08-21 16:32:19767 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44768 EXPECT_FALSE(d.received_data_before_response());
769 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19770 EXPECT_EQ("", r->GetSocketAddress().host());
771 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04772
773 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19774 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44775 }
776}
777
778TEST_F(URLRequestTest, DataURLImageTest) {
779 TestDelegate d;
780 {
781 // Use our nice little Chrome logo.
[email protected]f7022f32014-08-21 16:32:19782 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:19783 GURL(
davidben151423e2015-03-23 18:48:36784 "data:image/png;base64,"
785 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
786 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
787 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
788 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
789 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
790 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
791 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
792 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
793 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
794 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
795 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
796 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
797 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
798 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
799 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
800 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
801 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
802 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
803 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
804 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44805
[email protected]f7022f32014-08-21 16:32:19806 r->Start();
807 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44808
[email protected]255620da2013-08-19 13:14:29809 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44810
[email protected]f7022f32014-08-21 16:32:19811 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44812 EXPECT_FALSE(d.received_data_before_response());
813 EXPECT_EQ(d.bytes_received(), 911);
[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]5ecf7cb282014-05-11 01:49:55822#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44823TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15824 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44825 PathService::Get(base::FILE_EXE, &app_path);
826 GURL app_url = FilePathToFileURL(app_path);
827
828 TestDelegate d;
829 {
davidben151423e2015-03-23 18:48:36830 scoped_ptr<URLRequest> r(
831 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44832
[email protected]f7022f32014-08-21 16:32:19833 r->Start();
834 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44835
[email protected]255620da2013-08-19 13:14:29836 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44837
avibf0746c2015-12-09 19:53:14838 int64_t file_size = -1;
[email protected]56285702013-12-04 18:22:49839 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44840
[email protected]f7022f32014-08-21 16:32:19841 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44842 EXPECT_EQ(1, d.response_started_count());
843 EXPECT_FALSE(d.received_data_before_response());
844 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19845 EXPECT_EQ("", r->GetSocketAddress().host());
846 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04847
848 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19849 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44850 }
851}
852
[email protected]ba40bb762012-12-17 07:11:04853TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15854 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04855 PathService::Get(base::FILE_EXE, &app_path);
856 GURL app_url = FilePathToFileURL(app_path);
857
858 TestDelegate d;
859 {
davidben151423e2015-03-23 18:48:36860 scoped_ptr<URLRequest> r(
861 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04862
[email protected]f7022f32014-08-21 16:32:19863 r->Start();
864 EXPECT_TRUE(r->is_pending());
865 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04866 }
[email protected]79e1fd62013-06-20 06:50:04867 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04868 // destroyed.
[email protected]255620da2013-08-19 13:14:29869 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04870}
871
[email protected]316c1e5e2012-09-12 15:17:44872TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
873 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17874 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44875 FillBuffer(buffer.get(), buffer_size);
876
[email protected]6cdfd7f2013-02-08 20:40:15877 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52878 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44879 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30880 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44881
avibf0746c2015-12-09 19:53:14882 int64_t file_size;
[email protected]56285702013-12-04 18:22:49883 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44884
885 const size_t first_byte_position = 500;
886 const size_t last_byte_position = buffer_size - first_byte_position;
887 const size_t content_length = last_byte_position - first_byte_position + 1;
888 std::string partial_buffer_string(buffer.get() + first_byte_position,
889 buffer.get() + last_byte_position + 1);
890
891 TestDelegate d;
892 {
davidben151423e2015-03-23 18:48:36893 scoped_ptr<URLRequest> r(
894 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44895
896 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38897 headers.SetHeader(
898 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59899 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38900 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19901 r->SetExtraRequestHeaders(headers);
902 r->Start();
903 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44904
[email protected]255620da2013-08-19 13:14:29905 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19906 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44907 EXPECT_EQ(1, d.response_started_count());
908 EXPECT_FALSE(d.received_data_before_response());
909 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
910 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
911 EXPECT_TRUE(partial_buffer_string == d.data_received());
912 }
913
[email protected]dd3aa792013-07-16 19:10:23914 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44915}
916
917TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
918 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17919 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44920 FillBuffer(buffer.get(), buffer_size);
921
[email protected]6cdfd7f2013-02-08 20:40:15922 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52923 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44924 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30925 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44926
avibf0746c2015-12-09 19:53:14927 int64_t file_size;
[email protected]56285702013-12-04 18:22:49928 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44929
930 const size_t first_byte_position = 500;
931 const size_t last_byte_position = buffer_size - 1;
932 const size_t content_length = last_byte_position - first_byte_position + 1;
933 std::string partial_buffer_string(buffer.get() + first_byte_position,
934 buffer.get() + last_byte_position + 1);
935
936 TestDelegate d;
937 {
davidben151423e2015-03-23 18:48:36938 scoped_ptr<URLRequest> r(
939 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44940
941 HttpRequestHeaders headers;
942 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59943 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38944 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19945 r->SetExtraRequestHeaders(headers);
946 r->Start();
947 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44948
[email protected]255620da2013-08-19 13:14:29949 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19950 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44951 EXPECT_EQ(1, d.response_started_count());
952 EXPECT_FALSE(d.received_data_before_response());
953 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
954 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
955 EXPECT_TRUE(partial_buffer_string == d.data_received());
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
961TEST_F(URLRequestTest, FileTestMultipleRanges) {
962 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17963 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44964 FillBuffer(buffer.get(), buffer_size);
965
[email protected]6cdfd7f2013-02-08 20:40:15966 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52967 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44968 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30969 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44970
avibf0746c2015-12-09 19:53:14971 int64_t file_size;
[email protected]56285702013-12-04 18:22:49972 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44973
974 TestDelegate d;
975 {
davidben151423e2015-03-23 18:48:36976 scoped_ptr<URLRequest> r(
977 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44978
979 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38980 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19981 r->SetExtraRequestHeaders(headers);
982 r->Start();
983 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44984
[email protected]255620da2013-08-19 13:14:29985 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44986 EXPECT_TRUE(d.request_failed());
987 }
988
[email protected]dd3aa792013-07-16 19:10:23989 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44990}
991
[email protected]3ca8b362013-11-11 22:18:07992TEST_F(URLRequestTest, AllowFileURLs) {
993 base::ScopedTempDir temp_dir;
994 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
995 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52996 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07997 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:30998 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:59999 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071000
1001 {
1002 TestDelegate d;
1003 TestNetworkDelegate network_delegate;
1004 network_delegate.set_can_access_files(true);
1005 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:361006 scoped_ptr<URLRequest> r(
1007 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191008 r->Start();
[email protected]3ca8b362013-11-11 22:18:071009 base::RunLoop().Run();
1010 EXPECT_FALSE(d.request_failed());
1011 EXPECT_EQ(test_data, d.data_received());
1012 }
1013
1014 {
1015 TestDelegate d;
1016 TestNetworkDelegate network_delegate;
1017 network_delegate.set_can_access_files(false);
1018 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:361019 scoped_ptr<URLRequest> r(
1020 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191021 r->Start();
[email protected]3ca8b362013-11-11 22:18:071022 base::RunLoop().Run();
1023 EXPECT_TRUE(d.request_failed());
1024 EXPECT_EQ("", d.data_received());
1025 }
1026}
1027
[email protected]316c1e5e2012-09-12 15:17:441028
1029TEST_F(URLRequestTest, FileDirCancelTest) {
1030 // Put in mock resource provider.
1031 NetModule::SetResourceProvider(TestNetResourceProvider);
1032
1033 TestDelegate d;
1034 {
[email protected]6cdfd7f2013-02-08 20:40:151035 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441036 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1037 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1038 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1039
[email protected]f7022f32014-08-21 16:32:191040 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361041 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191042 req->Start();
1043 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441044
1045 d.set_cancel_in_received_data_pending(true);
1046
[email protected]255620da2013-08-19 13:14:291047 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441048 }
1049
1050 // Take out mock resource provider.
1051 NetModule::SetResourceProvider(NULL);
1052}
1053
[email protected]5f9581402013-10-30 13:08:321054TEST_F(URLRequestTest, FileDirOutputSanity) {
1055 // Verify the general sanity of the the output of the file:
1056 // directory lister by checking for the output of a known existing
1057 // file.
1058 const char sentinel_name[] = "filedir-sentinel";
1059
1060 base::FilePath path;
1061 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471062 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321063
1064 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191065 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361066 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191067 req->Start();
[email protected]5f9581402013-10-30 13:08:321068 base::RunLoop().Run();
1069
1070 // Generate entry for the sentinel file.
1071 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581072 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491073 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321074 EXPECT_GT(info.size, 0);
1075 std::string sentinel_output = GetDirectoryListingEntry(
1076 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1077 std::string(sentinel_name),
1078 false /* is_dir */,
1079 info.size,
1080 info.last_modified);
1081
1082 ASSERT_LT(0, d.bytes_received());
1083 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191084 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:321085 // Check for the entry generated for the "sentinel" file.
1086 const std::string& data = d.data_received();
1087 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1088}
1089
[email protected]316c1e5e2012-09-12 15:17:441090TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1091 // There is an implicit redirect when loading a file path that matches a
1092 // directory and does not end with a slash. Ensure that following such
1093 // redirects does not crash. See http://crbug.com/18686.
1094
[email protected]6cdfd7f2013-02-08 20:40:151095 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441096 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471097 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441098
1099 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191100 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361101 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191102 req->Start();
[email protected]255620da2013-08-19 13:14:291103 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441104
1105 ASSERT_EQ(1, d.received_redirect_count());
1106 ASSERT_LT(0, d.bytes_received());
1107 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191108 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441109}
1110
1111#if defined(OS_WIN)
1112// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1113TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1114 TestDelegate d;
davidben151423e2015-03-23 18:48:361115 scoped_ptr<URLRequest> req(
1116 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191117 req->Start();
[email protected]255620da2013-08-19 13:14:291118 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441119
1120 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191121 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441122}
[email protected]5ecf7cb282014-05-11 01:49:551123#endif // defined(OS_WIN)
1124
1125#endif // !defined(DISABLE_FILE_SUPPORT)
1126
1127TEST_F(URLRequestTest, InvalidUrlTest) {
1128 TestDelegate d;
1129 {
[email protected]f7022f32014-08-21 16:32:191130 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361131 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551132
[email protected]f7022f32014-08-21 16:32:191133 r->Start();
1134 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551135
1136 base::RunLoop().Run();
1137 EXPECT_TRUE(d.request_failed());
1138 }
1139}
1140
jochen0e3b3a62014-09-16 18:31:231141TEST_F(URLRequestTest, InvalidReferrerTest) {
1142 TestURLRequestContext context;
1143 TestNetworkDelegate network_delegate;
1144 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1145 context.set_network_delegate(&network_delegate);
1146 TestDelegate d;
davidben151423e2015-03-23 18:48:361147 scoped_ptr<URLRequest> req(
1148 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231149 req->SetReferrer("https://somewhere.com/");
1150
1151 req->Start();
1152 base::RunLoop().Run();
1153 EXPECT_TRUE(d.request_failed());
1154}
1155
[email protected]5ecf7cb282014-05-11 01:49:551156#if defined(OS_WIN)
1157TEST_F(URLRequestTest, ResolveShortcutTest) {
1158 base::FilePath app_path;
1159 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471160 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551161 app_path = app_path.AppendASCII("with-headers.html");
1162
1163 std::wstring lnk_path = app_path.value() + L".lnk";
1164
1165 base::win::ScopedCOMInitializer com_initializer;
1166
1167 // Temporarily create a shortcut for test
1168 {
1169 base::win::ScopedComPtr<IShellLink> shell;
1170 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1171 CLSCTX_INPROC_SERVER)));
1172 base::win::ScopedComPtr<IPersistFile> persist;
1173 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1174 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1175 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1176 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1177 }
1178
1179 TestDelegate d;
1180 {
[email protected]f7022f32014-08-21 16:32:191181 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361182 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551183
[email protected]f7022f32014-08-21 16:32:191184 r->Start();
1185 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551186
1187 base::RunLoop().Run();
1188
1189 WIN32_FILE_ATTRIBUTE_DATA data;
1190 GetFileAttributesEx(app_path.value().c_str(),
1191 GetFileExInfoStandard, &data);
1192 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1193 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1194 FILE_ATTRIBUTE_NORMAL, NULL);
1195 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1196 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1197 DWORD read_size;
1198 BOOL result;
1199 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1200 &read_size, NULL);
1201 std::string content(buffer.get(), read_size);
1202 CloseHandle(file);
1203
[email protected]f7022f32014-08-21 16:32:191204 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551205 EXPECT_EQ(1, d.received_redirect_count());
1206 EXPECT_EQ(content, d.data_received());
1207 }
1208
1209 // Clean the shortcut
1210 DeleteFile(lnk_path.c_str());
1211}
1212#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441213
1214// Custom URLRequestJobs for use with interceptor tests
1215class RestartTestJob : public URLRequestTestJob {
1216 public:
1217 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1218 : URLRequestTestJob(request, network_delegate, true) {}
1219 protected:
dchengb03027d2014-10-21 12:00:201220 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441221 private:
dchengb03027d2014-10-21 12:00:201222 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441223};
1224
1225class CancelTestJob : public URLRequestTestJob {
1226 public:
1227 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1228 : URLRequestTestJob(request, network_delegate, true) {}
1229 protected:
dchengb03027d2014-10-21 12:00:201230 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441231 private:
dchengb03027d2014-10-21 12:00:201232 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441233};
1234
1235class CancelThenRestartTestJob : public URLRequestTestJob {
1236 public:
1237 explicit CancelThenRestartTestJob(URLRequest* request,
1238 NetworkDelegate* network_delegate)
1239 : URLRequestTestJob(request, network_delegate, true) {
1240 }
1241 protected:
dchengb03027d2014-10-21 12:00:201242 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441243 request_->Cancel();
1244 this->NotifyRestartRequired();
1245 }
1246 private:
dchengb03027d2014-10-21 12:00:201247 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441248};
1249
bengr1bf8e942014-11-07 01:36:501250// An Interceptor for use with interceptor tests.
1251class MockURLRequestInterceptor : public URLRequestInterceptor {
1252 public:
1253 // Static getters for canned response header and data strings.
1254 static std::string ok_data() {
1255 return URLRequestTestJob::test_data_1();
1256 }
1257
1258 static std::string ok_headers() {
1259 return URLRequestTestJob::test_headers();
1260 }
1261
1262 static std::string redirect_data() {
1263 return std::string();
1264 }
1265
1266 static std::string redirect_headers() {
1267 return URLRequestTestJob::test_redirect_headers();
1268 }
1269
1270 static std::string error_data() {
1271 return std::string("ohhh nooooo mr. bill!");
1272 }
1273
1274 static std::string error_headers() {
1275 return URLRequestTestJob::test_error_headers();
1276 }
1277
1278 MockURLRequestInterceptor()
1279 : intercept_main_request_(false), restart_main_request_(false),
1280 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1281 simulate_main_network_error_(false),
1282 intercept_redirect_(false), cancel_redirect_request_(false),
1283 intercept_final_response_(false), cancel_final_request_(false),
1284 use_url_request_http_job_(false),
1285 did_intercept_main_(false), did_restart_main_(false),
1286 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1287 did_simulate_error_main_(false),
1288 did_intercept_redirect_(false), did_cancel_redirect_(false),
1289 did_intercept_final_(false), did_cancel_final_(false) {
1290 }
1291
1292 ~MockURLRequestInterceptor() override {
1293 }
1294
1295 // URLRequestInterceptor implementation:
1296 URLRequestJob* MaybeInterceptRequest(
1297 URLRequest* request,
1298 NetworkDelegate* network_delegate) const override {
1299 if (restart_main_request_) {
1300 restart_main_request_ = false;
1301 did_restart_main_ = true;
1302 return new RestartTestJob(request, network_delegate);
1303 }
1304 if (cancel_main_request_) {
1305 cancel_main_request_ = false;
1306 did_cancel_main_ = true;
1307 return new CancelTestJob(request, network_delegate);
1308 }
1309 if (cancel_then_restart_main_request_) {
1310 cancel_then_restart_main_request_ = false;
1311 did_cancel_then_restart_main_ = true;
1312 return new CancelThenRestartTestJob(request, network_delegate);
1313 }
1314 if (simulate_main_network_error_) {
1315 simulate_main_network_error_ = false;
1316 did_simulate_error_main_ = true;
1317 if (use_url_request_http_job_) {
1318 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1319 }
1320 // This job will result in error since the requested URL is not one of the
1321 // URLs supported by these tests.
1322 return new URLRequestTestJob(request, network_delegate, true);
1323 }
1324 if (!intercept_main_request_)
1325 return nullptr;
1326 intercept_main_request_ = false;
1327 did_intercept_main_ = true;
1328 URLRequestTestJob* job = new URLRequestTestJob(request,
1329 network_delegate,
1330 main_headers_,
1331 main_data_,
1332 true);
1333 job->set_load_timing_info(main_request_load_timing_info_);
1334 return job;
1335 }
1336
1337 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1338 NetworkDelegate* network_delegate,
1339 const GURL& location) const override {
1340 if (cancel_redirect_request_) {
1341 cancel_redirect_request_ = false;
1342 did_cancel_redirect_ = true;
1343 return new CancelTestJob(request, network_delegate);
1344 }
1345 if (!intercept_redirect_)
1346 return nullptr;
1347 intercept_redirect_ = false;
1348 did_intercept_redirect_ = true;
1349 if (use_url_request_http_job_) {
1350 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1351 }
1352 return new URLRequestTestJob(request,
1353 network_delegate,
1354 redirect_headers_,
1355 redirect_data_,
1356 true);
1357 }
1358
1359 URLRequestJob* MaybeInterceptResponse(
1360 URLRequest* request,
1361 NetworkDelegate* network_delegate) const override {
1362 if (cancel_final_request_) {
1363 cancel_final_request_ = false;
1364 did_cancel_final_ = true;
1365 return new CancelTestJob(request, network_delegate);
1366 }
1367 if (!intercept_final_response_)
1368 return nullptr;
1369 intercept_final_response_ = false;
1370 did_intercept_final_ = true;
1371 if (use_url_request_http_job_) {
1372 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1373 }
1374 return new URLRequestTestJob(request,
1375 network_delegate,
1376 final_headers_,
1377 final_data_,
1378 true);
1379 }
1380
1381 void set_intercept_main_request(bool intercept_main_request) {
1382 intercept_main_request_ = intercept_main_request;
1383 }
1384
1385 void set_main_headers(const std::string& main_headers) {
1386 main_headers_ = main_headers;
1387 }
1388
1389 void set_main_data(const std::string& main_data) {
1390 main_data_ = main_data;
1391 }
1392
1393 void set_main_request_load_timing_info(
1394 const LoadTimingInfo& main_request_load_timing_info) {
1395 main_request_load_timing_info_ = main_request_load_timing_info;
1396 }
1397
1398 void set_restart_main_request(bool restart_main_request) {
1399 restart_main_request_ = restart_main_request;
1400 }
1401
1402 void set_cancel_main_request(bool cancel_main_request) {
1403 cancel_main_request_ = cancel_main_request;
1404 }
1405
1406 void set_cancel_then_restart_main_request(
1407 bool cancel_then_restart_main_request) {
1408 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1409 }
1410
1411 void set_simulate_main_network_error(bool simulate_main_network_error) {
1412 simulate_main_network_error_ = simulate_main_network_error;
1413 }
1414
1415 void set_intercept_redirect(bool intercept_redirect) {
1416 intercept_redirect_ = intercept_redirect;
1417 }
1418
1419 void set_redirect_headers(const std::string& redirect_headers) {
1420 redirect_headers_ = redirect_headers;
1421 }
1422
1423 void set_redirect_data(const std::string& redirect_data) {
1424 redirect_data_ = redirect_data;
1425 }
1426
1427 void set_cancel_redirect_request(bool cancel_redirect_request) {
1428 cancel_redirect_request_ = cancel_redirect_request;
1429 }
1430
1431 void set_intercept_final_response(bool intercept_final_response) {
1432 intercept_final_response_ = intercept_final_response;
1433 }
1434
1435 void set_final_headers(const std::string& final_headers) {
1436 final_headers_ = final_headers;
1437 }
1438
1439 void set_final_data(const std::string& final_data) {
1440 final_data_ = final_data;
1441 }
1442
1443 void set_cancel_final_request(bool cancel_final_request) {
1444 cancel_final_request_ = cancel_final_request;
1445 }
1446
1447 void set_use_url_request_http_job(bool use_url_request_http_job) {
1448 use_url_request_http_job_ = use_url_request_http_job;
1449 }
1450
1451 bool did_intercept_main() const {
1452 return did_intercept_main_;
1453 }
1454
1455 bool did_restart_main() const {
1456 return did_restart_main_;
1457 }
1458
1459 bool did_cancel_main() const {
1460 return did_cancel_main_;
1461 }
1462
1463 bool did_cancel_then_restart_main() const {
1464 return did_cancel_then_restart_main_;
1465 }
1466
1467 bool did_simulate_error_main() const {
1468 return did_simulate_error_main_;
1469 }
1470
1471 bool did_intercept_redirect() const {
1472 return did_intercept_redirect_;
1473 }
1474
1475 bool did_cancel_redirect() const {
1476 return did_cancel_redirect_;
1477 }
1478
1479 bool did_intercept_final() const {
1480 return did_intercept_final_;
1481 }
1482
1483 bool did_cancel_final() const {
1484 return did_cancel_final_;
1485 }
1486
1487 private:
1488 // Indicate whether to intercept the main request, and if so specify the
1489 // response to return and the LoadTimingInfo to use.
1490 mutable bool intercept_main_request_;
1491 mutable std::string main_headers_;
1492 mutable std::string main_data_;
1493 mutable LoadTimingInfo main_request_load_timing_info_;
1494
1495 // These indicate actions that can be taken within MaybeInterceptRequest.
1496 mutable bool restart_main_request_;
1497 mutable bool cancel_main_request_;
1498 mutable bool cancel_then_restart_main_request_;
1499 mutable bool simulate_main_network_error_;
1500
1501 // Indicate whether to intercept redirects, and if so specify the response to
1502 // return.
1503 mutable bool intercept_redirect_;
1504 mutable std::string redirect_headers_;
1505 mutable std::string redirect_data_;
1506
1507 // Cancel the request within MaybeInterceptRedirect.
1508 mutable bool cancel_redirect_request_;
1509
1510 // Indicate whether to intercept the final response, and if so specify the
1511 // response to return.
1512 mutable bool intercept_final_response_;
1513 mutable std::string final_headers_;
1514 mutable std::string final_data_;
1515
1516 // Cancel the final request within MaybeInterceptResponse.
1517 mutable bool cancel_final_request_;
1518
1519 // Instruct the interceptor to use a real URLRequestHTTPJob.
1520 mutable bool use_url_request_http_job_;
1521
1522 // These indicate if the interceptor did something or not.
1523 mutable bool did_intercept_main_;
1524 mutable bool did_restart_main_;
1525 mutable bool did_cancel_main_;
1526 mutable bool did_cancel_then_restart_main_;
1527 mutable bool did_simulate_error_main_;
1528 mutable bool did_intercept_redirect_;
1529 mutable bool did_cancel_redirect_;
1530 mutable bool did_intercept_final_;
1531 mutable bool did_cancel_final_;
1532};
1533
1534// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1535class URLRequestInterceptorTest : public URLRequestTest {
1536 public:
1537 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1538 }
1539
1540 ~URLRequestInterceptorTest() override {
1541 // URLRequestJobs may post clean-up tasks on destruction.
1542 base::RunLoop().RunUntilIdle();
1543 }
1544
1545 void SetUpFactory() override {
1546 interceptor_ = new MockURLRequestInterceptor();
1547 job_factory_.reset(new URLRequestInterceptingJobFactory(
1548 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1549 }
1550
1551 MockURLRequestInterceptor* interceptor() const {
1552 return interceptor_;
1553 }
1554
1555 private:
1556 MockURLRequestInterceptor* interceptor_;
1557};
1558
1559TEST_F(URLRequestInterceptorTest, Intercept) {
1560 // Intercept the main request and respond with a simple response.
1561 interceptor()->set_intercept_main_request(true);
1562 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1563 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591564 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501565 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361566 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501567 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1568 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1569 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1570 req->SetUserData(nullptr, user_data0);
1571 req->SetUserData(&user_data1, user_data1);
1572 req->SetUserData(&user_data2, user_data2);
1573 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191574 req->Start();
[email protected]255620da2013-08-19 13:14:291575 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591576
bengr1bf8e942014-11-07 01:36:501577 // Make sure we can retrieve our specific user data.
1578 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1579 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1580 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591581
bengr1bf8e942014-11-07 01:36:501582 // Check that we got one good response.
1583 EXPECT_TRUE(req->status().is_success());
1584 EXPECT_EQ(200, req->response_headers()->response_code());
1585 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1586 EXPECT_EQ(1, d.response_started_count());
1587 EXPECT_EQ(0, d.received_redirect_count());
1588}
[email protected]2bba3252013-04-08 19:50:591589
bengr1bf8e942014-11-07 01:36:501590TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1591 // Intercept the main request and respond with a redirect.
1592 interceptor()->set_intercept_main_request(true);
1593 interceptor()->set_main_headers(
1594 MockURLRequestInterceptor::redirect_headers());
1595 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1596
1597 // Intercept that redirect and respond with a final OK response.
1598 interceptor()->set_intercept_redirect(true);
1599 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1600 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1601
1602 TestDelegate d;
1603 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361604 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501605 req->set_method("GET");
1606 req->Start();
1607 base::RunLoop().Run();
1608
1609 // Check that the interceptor got called as expected.
1610 EXPECT_TRUE(interceptor()->did_intercept_main());
1611 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1612
1613 // Check that we got one good response.
1614 EXPECT_TRUE(req->status().is_success());
1615 if (req->status().is_success())
1616 EXPECT_EQ(200, req->response_headers()->response_code());
1617
1618 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1619 EXPECT_EQ(1, d.response_started_count());
1620 EXPECT_EQ(0, d.received_redirect_count());
1621}
1622
1623TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1624 // Intercept the main request to generate a server error response.
1625 interceptor()->set_intercept_main_request(true);
1626 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1627 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1628
1629 // Intercept that error and respond with an OK response.
1630 interceptor()->set_intercept_final_response(true);
1631 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1632 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1633
1634 TestDelegate d;
1635 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361636 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501637 req->set_method("GET");
1638 req->Start();
1639 base::RunLoop().Run();
1640
1641 // Check that the interceptor got called as expected.
1642 EXPECT_TRUE(interceptor()->did_intercept_main());
1643 EXPECT_TRUE(interceptor()->did_intercept_final());
1644
1645 // Check that we got one good response.
1646 EXPECT_TRUE(req->status().is_success());
1647 EXPECT_EQ(200, req->response_headers()->response_code());
1648 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1649 EXPECT_EQ(1, d.response_started_count());
1650 EXPECT_EQ(0, d.received_redirect_count());
1651}
1652
1653TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1654 // Intercept the main request to simulate a network error.
1655 interceptor()->set_simulate_main_network_error(true);
1656
1657 // Intercept that error and respond with an OK response.
1658 interceptor()->set_intercept_final_response(true);
1659 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1660 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1661
1662 TestDelegate d;
1663 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361664 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501665 req->set_method("GET");
1666 req->Start();
1667 base::RunLoop().Run();
1668
1669 // Check that the interceptor got called as expected.
1670 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1671 EXPECT_TRUE(interceptor()->did_intercept_final());
1672
1673 // Check that we received one good response.
1674 EXPECT_TRUE(req->status().is_success());
1675 EXPECT_EQ(200, req->response_headers()->response_code());
1676 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1677 EXPECT_EQ(1, d.response_started_count());
1678 EXPECT_EQ(0, d.received_redirect_count());
1679}
1680
1681TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1682 // Restart the main request.
1683 interceptor()->set_restart_main_request(true);
1684
1685 // then intercept the new main request and respond with an OK response
1686 interceptor()->set_intercept_main_request(true);
1687 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1688 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1689
1690 TestDelegate d;
1691 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361692 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501693 req->set_method("GET");
1694 req->Start();
1695 base::RunLoop().Run();
1696
1697 // Check that the interceptor got called as expected.
1698 EXPECT_TRUE(interceptor()->did_restart_main());
1699 EXPECT_TRUE(interceptor()->did_intercept_main());
1700
1701 // Check that we received one good response.
1702 EXPECT_TRUE(req->status().is_success());
1703 if (req->status().is_success())
1704 EXPECT_EQ(200, req->response_headers()->response_code());
1705
1706 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1707 EXPECT_EQ(1, d.response_started_count());
1708 EXPECT_EQ(0, d.received_redirect_count());
1709}
1710
1711TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1712 // Intercept the main request and cancel from within the restarted job.
1713 interceptor()->set_cancel_main_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_cancel_main());
1729 EXPECT_FALSE(interceptor()->did_intercept_final());
1730
1731 // Check that we see a canceled request.
1732 EXPECT_FALSE(req->status().is_success());
1733 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1734}
1735
1736TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1737 // Intercept the main request and respond with a redirect.
1738 interceptor()->set_intercept_main_request(true);
1739 interceptor()->set_main_headers(
1740 MockURLRequestInterceptor::redirect_headers());
1741 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1742
1743 // Intercept the redirect and cancel from within that job.
1744 interceptor()->set_cancel_redirect_request(true);
1745
1746 // Set up to intercept the final response and override it with an OK response.
1747 interceptor()->set_intercept_final_response(true);
1748 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1749 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1750
1751 TestDelegate d;
1752 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361753 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501754 req->set_method("GET");
1755 req->Start();
1756 base::RunLoop().Run();
1757
1758 // Check that the interceptor got called as expected.
1759 EXPECT_TRUE(interceptor()->did_intercept_main());
1760 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1761 EXPECT_FALSE(interceptor()->did_intercept_final());
1762
1763 // Check that we see a canceled request.
1764 EXPECT_FALSE(req->status().is_success());
1765 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1766}
1767
1768TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1769 // Intercept the main request to simulate a network error.
1770 interceptor()->set_simulate_main_network_error(true);
1771
1772 // Set up to intercept final the response and cancel from within that job.
1773 interceptor()->set_cancel_final_request(true);
1774
1775 TestDelegate d;
1776 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361777 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501778 req->set_method("GET");
1779 req->Start();
1780 base::RunLoop().Run();
1781
1782 // Check that the interceptor got called as expected.
1783 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1784 EXPECT_TRUE(interceptor()->did_cancel_final());
1785
1786 // Check that we see a canceled request.
1787 EXPECT_FALSE(req->status().is_success());
1788 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1789}
1790
1791TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1792 // Intercept the main request and cancel then restart from within that job.
1793 interceptor()->set_cancel_then_restart_main_request(true);
1794
1795 // Set up to intercept the final response and override it with an OK response.
1796 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501797 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1798 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501799
1800 TestDelegate d;
1801 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361802 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501803 req->set_method("GET");
1804 req->Start();
1805 base::RunLoop().Run();
1806
1807 // Check that the interceptor got called as expected.
1808 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1809 EXPECT_FALSE(interceptor()->did_intercept_final());
1810
1811 // Check that we see a canceled request.
1812 EXPECT_FALSE(req->status().is_success());
1813 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591814}
1815
1816// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1817// reused. |connect_time_flags| is used to indicate if there should be dns
1818// or SSL times, and |used_proxy| is used for proxy times.
1819LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1820 int connect_time_flags,
1821 bool used_proxy) {
1822 LoadTimingInfo load_timing;
1823 load_timing.socket_log_id = 1;
1824
1825 if (used_proxy) {
1826 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1827 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1828 }
1829
1830 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1831 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1832 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1833 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1834 }
1835 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1836 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1837 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1838 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1839 }
1840 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1841
1842 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1843 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1844 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1845 return load_timing;
1846}
1847
1848// Same as above, but in the case of a reused socket.
1849LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1850 bool used_proxy) {
1851 LoadTimingInfo load_timing;
1852 load_timing.socket_log_id = 1;
1853 load_timing.socket_reused = true;
1854
1855 if (used_proxy) {
1856 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1857 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1858 }
1859
1860 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1861 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1862 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1863 return load_timing;
1864}
1865
bengr1bf8e942014-11-07 01:36:501866LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1867 const LoadTimingInfo& job_load_timing,
1868 const URLRequestContext& context,
1869 MockURLRequestInterceptor* interceptor) {
1870 interceptor->set_intercept_main_request(true);
1871 interceptor->set_main_request_load_timing_info(job_load_timing);
1872 TestDelegate d;
1873 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361874 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501875 req->Start();
1876 base::RunLoop().Run();
1877
1878 LoadTimingInfo resulting_load_timing;
1879 req->GetLoadTimingInfo(&resulting_load_timing);
1880
1881 // None of these should be modified by the URLRequest.
1882 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1883 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1884 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1885 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1886 EXPECT_EQ(job_load_timing.receive_headers_end,
1887 resulting_load_timing.receive_headers_end);
1888
1889 return resulting_load_timing;
1890}
1891
[email protected]2bba3252013-04-08 19:50:591892// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501893TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591894 base::TimeTicks now = base::TimeTicks::Now();
1895 LoadTimingInfo job_load_timing =
1896 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1897
[email protected]2ca01e52013-10-31 22:05:191898 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501899 RunURLRequestInterceptorLoadTimingTest(
1900 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591901
1902 // Nothing should have been changed by the URLRequest.
1903 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1904 load_timing_result.proxy_resolve_start);
1905 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1906 load_timing_result.proxy_resolve_end);
1907 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1908 load_timing_result.connect_timing.dns_start);
1909 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1910 load_timing_result.connect_timing.dns_end);
1911 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1912 load_timing_result.connect_timing.connect_start);
1913 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1914 load_timing_result.connect_timing.connect_end);
1915 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1916 load_timing_result.connect_timing.ssl_start);
1917 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1918 load_timing_result.connect_timing.ssl_end);
1919
1920 // Redundant sanity check.
1921 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1922}
1923
1924// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501925TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591926 base::TimeTicks now = base::TimeTicks::Now();
1927 LoadTimingInfo job_load_timing =
1928 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1929
[email protected]2ca01e52013-10-31 22:05:191930 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501931 RunURLRequestInterceptorLoadTimingTest(
1932 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591933
1934 // Nothing should have been changed by the URLRequest.
1935 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1936 load_timing_result.proxy_resolve_start);
1937 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1938 load_timing_result.proxy_resolve_end);
1939 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1940 load_timing_result.connect_timing.dns_start);
1941 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1942 load_timing_result.connect_timing.dns_end);
1943 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1944 load_timing_result.connect_timing.connect_start);
1945 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1946 load_timing_result.connect_timing.connect_end);
1947 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1948 load_timing_result.connect_timing.ssl_start);
1949 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1950 load_timing_result.connect_timing.ssl_end);
1951
1952 // Redundant sanity check.
1953 TestLoadTimingNotReusedWithProxy(load_timing_result,
1954 CONNECT_TIMING_HAS_SSL_TIMES);
1955}
1956
1957// Make sure that URLRequest correctly adjusts proxy times when they're before
1958// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101959// the case of reusing a SPDY session. The connected socket is not considered
1960// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591961//
1962// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501963TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591964 base::TimeTicks now = base::TimeTicks::Now();
1965 LoadTimingInfo job_load_timing =
1966 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1967 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1968 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1969 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1970 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1971 job_load_timing.connect_timing.connect_start =
1972 now - base::TimeDelta::FromDays(2);
1973 job_load_timing.connect_timing.connect_end =
1974 now - base::TimeDelta::FromDays(1);
1975
[email protected]2ca01e52013-10-31 22:05:191976 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501977 RunURLRequestInterceptorLoadTimingTest(
1978 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591979
1980 // Proxy times, connect times, and DNS times should all be replaced with
1981 // 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 EXPECT_EQ(load_timing_result.request_start,
1987 load_timing_result.connect_timing.dns_start);
1988 EXPECT_EQ(load_timing_result.request_start,
1989 load_timing_result.connect_timing.dns_end);
1990 EXPECT_EQ(load_timing_result.request_start,
1991 load_timing_result.connect_timing.connect_start);
1992 EXPECT_EQ(load_timing_result.request_start,
1993 load_timing_result.connect_timing.connect_end);
1994
1995 // Other times should have been left null.
1996 TestLoadTimingNotReusedWithProxy(load_timing_result,
1997 CONNECT_TIMING_HAS_DNS_TIMES);
1998}
1999
2000// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502001TEST_F(URLRequestInterceptorTest,
2002 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592003 base::TimeTicks now = base::TimeTicks::Now();
2004 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2005 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2006 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2007
[email protected]2ca01e52013-10-31 22:05:192008 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502009 RunURLRequestInterceptorLoadTimingTest(
2010 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592011
2012 // Proxy times and connect times should all be replaced with request_start.
2013 EXPECT_EQ(load_timing_result.request_start,
2014 load_timing_result.proxy_resolve_start);
2015 EXPECT_EQ(load_timing_result.request_start,
2016 load_timing_result.proxy_resolve_end);
2017
2018 // Other times should have been left null.
2019 TestLoadTimingReusedWithProxy(load_timing_result);
2020}
2021
2022// Make sure that URLRequest correctly adjusts connect times when they're before
2023// |request_start|, due to reusing a connected socket. The connected socket is
2024// not considered reused in this test (May be a preconnect).
2025//
2026// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502027TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592028 base::TimeTicks now = base::TimeTicks::Now();
2029 LoadTimingInfo job_load_timing =
2030 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2031 job_load_timing.connect_timing.connect_start =
2032 now - base::TimeDelta::FromDays(1);
2033 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2034 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2035 job_load_timing.connect_timing.connect_end =
2036 now - base::TimeDelta::FromDays(4);
2037
[email protected]2ca01e52013-10-31 22:05:192038 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502039 RunURLRequestInterceptorLoadTimingTest(
2040 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592041
2042 // Connect times, and SSL times should be replaced with request_start.
2043 EXPECT_EQ(load_timing_result.request_start,
2044 load_timing_result.connect_timing.connect_start);
2045 EXPECT_EQ(load_timing_result.request_start,
2046 load_timing_result.connect_timing.ssl_start);
2047 EXPECT_EQ(load_timing_result.request_start,
2048 load_timing_result.connect_timing.ssl_end);
2049 EXPECT_EQ(load_timing_result.request_start,
2050 load_timing_result.connect_timing.connect_end);
2051
2052 // Other times should have been left null.
2053 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2054}
2055
2056// Make sure that URLRequest correctly adjusts connect times when they're before
2057// |request_start|, due to reusing a connected socket in the case that there
2058// are also proxy times. The connected socket is not considered reused in this
2059// test (May be a preconnect).
2060//
2061// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502062TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592063 base::TimeTicks now = base::TimeTicks::Now();
2064 LoadTimingInfo job_load_timing =
2065 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2066 job_load_timing.connect_timing.connect_start =
2067 now - base::TimeDelta::FromDays(1);
2068 job_load_timing.connect_timing.connect_end =
2069 now - base::TimeDelta::FromDays(2);
2070
[email protected]2ca01e52013-10-31 22:05:192071 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502072 RunURLRequestInterceptorLoadTimingTest(
2073 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592074
2075 // Connect times should be replaced with proxy_resolve_end.
2076 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2077 load_timing_result.connect_timing.connect_start);
2078 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2079 load_timing_result.connect_timing.connect_end);
2080
2081 // Other times should have been left null.
2082 TestLoadTimingNotReusedWithProxy(load_timing_result,
2083 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2084}
2085
[email protected]316c1e5e2012-09-12 15:17:442086// Check that two different URL requests have different identifiers.
2087TEST_F(URLRequestTest, Identifiers) {
2088 TestDelegate d;
2089 TestURLRequestContext context;
davidben151423e2015-03-23 18:48:362090 scoped_ptr<URLRequest> req(
2091 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2092 scoped_ptr<URLRequest> other_req(
2093 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442094
mmenke19378d22014-09-09 04:12:592095 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442096}
2097
blundellb8163592f2015-12-16 14:22:422098#if defined(OS_IOS)
2099// TODO(droger): Check that a failure to connect to the proxy is reported to
2100// the network delegate. crbug.com/496743
2101#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2102#else
2103#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2104#endif
2105TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442106 MockHostResolver host_resolver;
2107 host_resolver.rules()->AddSimulatedFailure("*");
2108
[email protected]ceefd7fd2012-11-29 00:36:242109 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442110 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2111
2112 TestDelegate d;
davidben151423e2015-03-23 18:48:362113 scoped_ptr<URLRequest> req(
2114 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192115 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442116
[email protected]f7022f32014-08-21 16:32:192117 req->Start();
[email protected]255620da2013-08-19 13:14:292118 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442119
2120 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192121 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152122 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192123 EXPECT_TRUE(req->proxy_server().IsEmpty());
2124 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2125 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442126
2127 EXPECT_EQ(1, network_delegate.error_count());
2128 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2129 EXPECT_EQ(1, network_delegate.completed_requests());
2130}
2131
[email protected]cba24642014-08-15 20:49:592132// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442133// content is empty.
2134TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2135 TestDelegate d;
davidben151423e2015-03-23 18:48:362136 scoped_ptr<URLRequest> req(
2137 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192138 req->Start();
[email protected]255620da2013-08-19 13:14:292139 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442140 EXPECT_EQ("", d.data_received());
2141 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2142}
2143
[email protected]5033ab82013-03-22 20:17:462144// Make sure that SetPriority actually sets the URLRequest's priority
2145// correctly, both before and after start.
2146TEST_F(URLRequestTest, SetPriorityBasic) {
2147 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192148 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362149 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192150 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462151
[email protected]f7022f32014-08-21 16:32:192152 req->SetPriority(LOW);
2153 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462154
[email protected]f7022f32014-08-21 16:32:192155 req->Start();
2156 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462157
[email protected]f7022f32014-08-21 16:32:192158 req->SetPriority(MEDIUM);
2159 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462160}
2161
2162// Make sure that URLRequest calls SetPriority on a job before calling
2163// Start on it.
2164TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2165 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192166 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362167 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192168 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462169
mmenkeed0498b2015-12-08 23:20:422170 RequestPriority job_priority;
2171 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
2172 req.get(), &default_network_delegate_, &job_priority));
2173 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2174 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462175
[email protected]f7022f32014-08-21 16:32:192176 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462177
[email protected]f7022f32014-08-21 16:32:192178 req->Start();
mmenkeed0498b2015-12-08 23:20:422179 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462180}
2181
2182// Make sure that URLRequest passes on its priority updates to its
2183// job.
2184TEST_F(URLRequestTest, SetJobPriority) {
2185 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192186 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362187 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462188
mmenkeed0498b2015-12-08 23:20:422189 RequestPriority job_priority;
2190 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
2191 req.get(), &default_network_delegate_, &job_priority));
2192 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462193
[email protected]f7022f32014-08-21 16:32:192194 req->SetPriority(LOW);
2195 req->Start();
mmenkeed0498b2015-12-08 23:20:422196 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462197
[email protected]f7022f32014-08-21 16:32:192198 req->SetPriority(MEDIUM);
2199 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422200 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462201}
2202
[email protected]bb1c4662013-11-14 00:00:072203// Setting the IGNORE_LIMITS load flag should be okay if the priority
2204// is MAXIMUM_PRIORITY.
2205TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2206 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192207 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362208 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192209 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072210
mmenkeed0498b2015-12-08 23:20:422211 RequestPriority job_priority;
2212 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
2213 req.get(), &default_network_delegate_, &job_priority));
2214 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072215
[email protected]f7022f32014-08-21 16:32:192216 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2217 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072218
[email protected]f7022f32014-08-21 16:32:192219 req->SetPriority(MAXIMUM_PRIORITY);
2220 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072221
[email protected]f7022f32014-08-21 16:32:192222 req->Start();
2223 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422224 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072225}
2226
nick5d570de92015-05-04 20:16:162227namespace {
2228
2229// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552230class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442231 public:
tommycli59a63432015-11-06 00:10:552232 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2233 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272234 }
tommycli59a63432015-11-06 00:10:552235
2236 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2237};
tommyclieae5f75f2015-11-05 19:07:272238
nick5d570de92015-05-04 20:16:162239} // namespace
2240
[email protected]f2f31b32013-01-16 23:24:092241TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442242 LocalHttpTestServer test_server;
2243 ASSERT_TRUE(test_server.Start());
2244
2245 TestURLRequestContext context;
2246 scoped_refptr<DelayedCookieMonster> delayed_cm =
2247 new DelayedCookieMonster();
2248 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502249 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442250
2251 // Set up a cookie.
2252 {
2253 TestNetworkDelegate network_delegate;
2254 context.set_network_delegate(&network_delegate);
2255 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192256 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552257 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362258 &d));
[email protected]f7022f32014-08-21 16:32:192259 req->Start();
[email protected]255620da2013-08-19 13:14:292260 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442261 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2262 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2263 EXPECT_EQ(1, network_delegate.set_cookie_count());
2264 }
2265
2266 // Verify that the cookie is set.
2267 {
2268 TestNetworkDelegate network_delegate;
2269 context.set_network_delegate(&network_delegate);
2270 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192271 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552272 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192273 req->Start();
[email protected]255620da2013-08-19 13:14:292274 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442275
2276 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2277 != std::string::npos);
2278 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2279 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2280 }
2281}
2282
[email protected]f2f31b32013-01-16 23:24:092283TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442284 LocalHttpTestServer test_server;
2285 ASSERT_TRUE(test_server.Start());
2286
2287 // Set up a cookie.
2288 {
2289 TestNetworkDelegate network_delegate;
2290 default_context_.set_network_delegate(&network_delegate);
2291 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192292 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552293 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362294 &d));
[email protected]f7022f32014-08-21 16:32:192295 req->Start();
[email protected]255620da2013-08-19 13:14:292296 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442297 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2298 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2299 }
2300
2301 // Verify that the cookie is set.
2302 {
2303 TestNetworkDelegate network_delegate;
2304 default_context_.set_network_delegate(&network_delegate);
2305 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192306 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552307 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192308 req->Start();
[email protected]255620da2013-08-19 13:14:292309 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442310
2311 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2312 != std::string::npos);
2313 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2314 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2315 }
2316
2317 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2318 {
2319 TestNetworkDelegate network_delegate;
2320 default_context_.set_network_delegate(&network_delegate);
2321 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192322 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552323 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192324 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2325 req->Start();
[email protected]255620da2013-08-19 13:14:292326 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442327
2328 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2329 == std::string::npos);
2330
2331 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2332 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2333 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2334 }
2335}
2336
2337TEST_F(URLRequestTest, DoNotSaveCookies) {
2338 LocalHttpTestServer test_server;
2339 ASSERT_TRUE(test_server.Start());
2340
2341 // Set up a cookie.
2342 {
2343 TestNetworkDelegate network_delegate;
2344 default_context_.set_network_delegate(&network_delegate);
2345 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192346 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552347 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362348 &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_EQ(0, network_delegate.blocked_get_cookies_count());
2353 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2354 EXPECT_EQ(1, network_delegate.set_cookie_count());
2355 }
2356
2357 // Try to set-up another cookie and update the previous cookie.
2358 {
2359 TestNetworkDelegate network_delegate;
2360 default_context_.set_network_delegate(&network_delegate);
2361 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192362 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552363 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362364 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192365 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2366 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442367
[email protected]255620da2013-08-19 13:14:292368 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442369
2370 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2371 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2372 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2373 EXPECT_EQ(0, network_delegate.set_cookie_count());
2374 }
2375
2376 // Verify the cookies weren't saved or updated.
2377 {
2378 TestNetworkDelegate network_delegate;
2379 default_context_.set_network_delegate(&network_delegate);
2380 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192381 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552382 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192383 req->Start();
[email protected]255620da2013-08-19 13:14:292384 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442385
2386 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2387 == std::string::npos);
2388 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2389 != std::string::npos);
2390
2391 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2392 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2393 EXPECT_EQ(0, network_delegate.set_cookie_count());
2394 }
2395}
2396
2397TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2398 LocalHttpTestServer test_server;
2399 ASSERT_TRUE(test_server.Start());
2400
2401 // Set up a cookie.
2402 {
2403 TestNetworkDelegate network_delegate;
2404 default_context_.set_network_delegate(&network_delegate);
2405 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192406 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552407 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362408 &d));
[email protected]f7022f32014-08-21 16:32:192409 req->Start();
[email protected]255620da2013-08-19 13:14:292410 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442411
2412 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2413 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2414 }
2415
2416 // Verify that the cookie is set.
2417 {
2418 TestNetworkDelegate network_delegate;
2419 default_context_.set_network_delegate(&network_delegate);
2420 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192421 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552422 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192423 req->Start();
[email protected]255620da2013-08-19 13:14:292424 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442425
2426 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2427 != std::string::npos);
2428
2429 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2430 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2431 }
2432
2433 // Verify that the cookie isn't sent.
2434 {
2435 TestNetworkDelegate network_delegate;
2436 default_context_.set_network_delegate(&network_delegate);
2437 TestDelegate d;
2438 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192439 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552440 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192441 req->Start();
[email protected]255620da2013-08-19 13:14:292442 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442443
2444 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2445 == std::string::npos);
2446
[email protected]22e045f2013-09-20 03:54:032447 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442448 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2449 }
2450}
2451
marqf14fff8d2015-12-02 15:52:292452// TODO(crbug.com/564656) This test is flaky on iOS.
2453#if defined(OS_IOS)
2454#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2455#else
2456#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2457#endif
[email protected]316c1e5e2012-09-12 15:17:442458TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2459 LocalHttpTestServer test_server;
2460 ASSERT_TRUE(test_server.Start());
2461
2462 // Set up a cookie.
2463 {
2464 TestNetworkDelegate network_delegate;
2465 default_context_.set_network_delegate(&network_delegate);
2466 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192467 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552468 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362469 &d));
[email protected]f7022f32014-08-21 16:32:192470 req->Start();
[email protected]255620da2013-08-19 13:14:292471 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442472
2473 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2474 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2475 }
2476
2477 // Try to set-up another cookie and update the previous cookie.
2478 {
2479 TestNetworkDelegate network_delegate;
2480 default_context_.set_network_delegate(&network_delegate);
2481 TestDelegate d;
2482 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192483 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552484 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362485 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192486 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442487
[email protected]255620da2013-08-19 13:14:292488 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442489
2490 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2491 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2492 }
2493
2494 // Verify the cookies weren't saved or updated.
2495 {
2496 TestNetworkDelegate network_delegate;
2497 default_context_.set_network_delegate(&network_delegate);
2498 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192499 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552500 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192501 req->Start();
[email protected]255620da2013-08-19 13:14:292502 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442503
2504 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2505 == std::string::npos);
2506 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2507 != std::string::npos);
2508
2509 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2510 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2511 }
2512}
2513
2514TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2515 LocalHttpTestServer test_server;
2516 ASSERT_TRUE(test_server.Start());
2517
2518 // Set up an empty cookie.
2519 {
2520 TestNetworkDelegate network_delegate;
2521 default_context_.set_network_delegate(&network_delegate);
2522 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192523 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552524 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192525 req->Start();
[email protected]255620da2013-08-19 13:14:292526 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442527
2528 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2529 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2530 EXPECT_EQ(0, network_delegate.set_cookie_count());
2531 }
2532}
2533
2534TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2535 LocalHttpTestServer test_server;
2536 ASSERT_TRUE(test_server.Start());
2537
2538 // Set up a cookie.
2539 {
2540 TestNetworkDelegate network_delegate;
2541 default_context_.set_network_delegate(&network_delegate);
2542 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192543 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552544 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362545 &d));
[email protected]f7022f32014-08-21 16:32:192546 req->Start();
[email protected]255620da2013-08-19 13:14:292547 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442548
2549 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2550 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2551 }
2552
2553 // Verify that the cookie is set.
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(
tommycli59a63432015-11-06 00:10:552559 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192560 req->Start();
[email protected]255620da2013-08-19 13:14:292561 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442562
2563 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2564 != std::string::npos);
2565
2566 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2567 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2568 }
2569
2570 // Verify that the cookie isn't sent.
2571 {
2572 TestNetworkDelegate network_delegate;
2573 default_context_.set_network_delegate(&network_delegate);
2574 TestDelegate d;
2575 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192576 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552577 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192578 req->Start();
[email protected]255620da2013-08-19 13:14:292579 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442580
2581 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2582 == std::string::npos);
2583
[email protected]22e045f2013-09-20 03:54:032584 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442585 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2586 }
2587}
2588
2589TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2590 LocalHttpTestServer test_server;
2591 ASSERT_TRUE(test_server.Start());
2592
2593 // Set up a cookie.
2594 {
2595 TestNetworkDelegate network_delegate;
2596 default_context_.set_network_delegate(&network_delegate);
2597 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192598 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552599 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362600 &d));
[email protected]f7022f32014-08-21 16:32:192601 req->Start();
[email protected]255620da2013-08-19 13:14:292602 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442603
2604 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2605 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2606 }
2607
2608 // Try to set-up another cookie and update the previous cookie.
2609 {
2610 TestNetworkDelegate network_delegate;
2611 default_context_.set_network_delegate(&network_delegate);
2612 TestDelegate d;
2613 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192614 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552615 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362616 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192617 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442618
[email protected]255620da2013-08-19 13:14:292619 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442620
2621 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2622 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2623 }
2624
2625 // Verify the cookies weren't saved or updated.
2626 {
2627 TestNetworkDelegate network_delegate;
2628 default_context_.set_network_delegate(&network_delegate);
2629 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192630 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552631 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192632 req->Start();
[email protected]255620da2013-08-19 13:14:292633 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442634
2635 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2636 == std::string::npos);
2637 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2638 != std::string::npos);
2639
2640 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2641 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2642 }
2643}
2644
mkwst3f3daac2015-02-26 20:15:262645TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2646 LocalHttpTestServer test_server;
2647 ASSERT_TRUE(test_server.Start());
2648
2649 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2650 // LocalHttpTestServer points).
2651 {
2652 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412653 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262654 default_context_.set_network_delegate(&network_delegate);
2655
2656 TestDelegate d;
2657 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2658 test_server.GetURL(
tommycli59a63432015-11-06 00:10:552659 "/set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
davidben151423e2015-03-23 18:48:362660 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262661 req->Start();
2662 base::RunLoop().Run();
2663 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2664 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2665 EXPECT_EQ(1, network_delegate.set_cookie_count());
2666 }
2667
2668 // Verify that the cookie is sent for first-party requests.
2669 {
2670 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412671 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262672 default_context_.set_network_delegate(&network_delegate);
2673 TestDelegate d;
2674 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552675 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2676 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst3f3daac2015-02-26 20:15:262677 req->Start();
2678 base::RunLoop().Run();
2679
2680 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2681 std::string::npos);
2682 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2683 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2684 }
2685
2686 // Verify that the cookie is not-sent for non-first-party requests.
2687 {
2688 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412689 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262690 default_context_.set_network_delegate(&network_delegate);
2691 TestDelegate d;
2692 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552693 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262694 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2695 req->Start();
2696 base::RunLoop().Run();
2697
2698 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2699 std::string::npos);
2700 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2701 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2702 }
2703}
2704
mkwst0513c9d2015-04-01 05:53:152705TEST_F(URLRequestTest, FirstPartyOnlyCookiesDisabled) {
2706 LocalHttpTestServer test_server;
2707 ASSERT_TRUE(test_server.Start());
2708
2709 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2710 // LocalHttpTestServer points).
2711 {
2712 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412713 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152714 default_context_.set_network_delegate(&network_delegate);
2715
2716 TestDelegate d;
2717 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2718 test_server.GetURL(
tommycli59a63432015-11-06 00:10:552719 "/set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
mkwst0513c9d2015-04-01 05:53:152720 DEFAULT_PRIORITY, &d));
2721 req->Start();
2722 base::RunLoop().Run();
2723 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2724 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2725 EXPECT_EQ(1, network_delegate.set_cookie_count());
2726 }
2727
2728 // Verify that the cookie is sent for first-party requests.
2729 {
2730 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412731 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152732 default_context_.set_network_delegate(&network_delegate);
2733 TestDelegate d;
2734 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552735 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2736 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst0513c9d2015-04-01 05:53:152737 req->Start();
2738 base::RunLoop().Run();
2739
2740 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2741 std::string::npos);
2742 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2743 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2744 }
2745
2746 // Verify that the cookie is also sent for non-first-party requests.
2747 {
2748 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412749 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152750 default_context_.set_network_delegate(&network_delegate);
2751 TestDelegate d;
2752 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552753 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst0513c9d2015-04-01 05:53:152754 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2755 req->Start();
2756 base::RunLoop().Run();
2757
jww79aceda2015-12-07 01:56:342758 EXPECT_NE(d.data_received().find("FirstPartyCookieToSet=1"),
2759 std::string::npos);
mkwst0513c9d2015-04-01 05:53:152760 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2761 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2762 }
2763}
2764
estark557a5eb82015-12-01 22:57:102765// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:362766TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:552767 EmbeddedTestServer http_server;
2768 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362769 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552770 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2771 https_server.AddDefaultHandlers(
2772 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2773 ASSERT_TRUE(http_server.Start());
2774 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362775
estarkb15166b2015-12-18 16:56:382776 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362777 TestURLRequestContext context(true);
2778 context.set_network_delegate(&network_delegate);
2779 context.Init();
2780
estarkb15166b2015-12-18 16:56:382781 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362782 {
2783 TestDelegate d;
2784 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102785 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362786 DEFAULT_PRIORITY, &d));
2787 req->Start();
2788 base::RunLoop().Run();
2789 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2790 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2791 }
2792
2793 // Verify that the cookie is not set.
2794 {
2795 TestDelegate d;
2796 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552797 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362798 req->Start();
2799 base::RunLoop().Run();
2800
jww79aceda2015-12-07 01:56:342801 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
2802 std::string::npos);
estarkcd39c11f2015-10-19 19:46:362803 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2804 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2805 }
2806}
2807
estarkb15166b2015-12-18 16:56:382808TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:552809 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2810 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362811 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552812 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362813
2814 TestNetworkDelegate network_delegate;
2815 TestURLRequestContext context(true);
2816 context.set_network_delegate(&network_delegate);
2817 context.Init();
2818
estarkb15166b2015-12-18 16:56:382819 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362820 {
2821 TestDelegate d;
tommycli59a63432015-11-06 00:10:552822 scoped_ptr<URLRequest> req(
estark557a5eb82015-12-01 22:57:102823 context.CreateRequest(https_server.GetURL("/set-cookie?__Secure-foo=1"),
tommycli59a63432015-11-06 00:10:552824 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362825 req->Start();
2826 base::RunLoop().Run();
2827 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2828 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2829 }
2830
2831 // Verify that the cookie is not set.
2832 {
2833 TestDelegate d;
2834 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552835 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362836 req->Start();
2837 base::RunLoop().Run();
2838
jww79aceda2015-12-07 01:56:342839 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362840 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2841 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2842 }
2843}
2844
estarkb15166b2015-12-18 16:56:382845TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:552846 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2847 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362848 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552849 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362850
estarkb15166b2015-12-18 16:56:382851 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362852 TestURLRequestContext context(true);
2853 context.set_network_delegate(&network_delegate);
2854 context.Init();
2855
estarkb15166b2015-12-18 16:56:382856 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362857 {
2858 TestDelegate d;
2859 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102860 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
tommycli59a63432015-11-06 00:10:552861 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362862 req->Start();
2863 base::RunLoop().Run();
2864 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2865 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2866 }
2867
2868 // Verify that the cookie is set.
2869 {
2870 TestDelegate d;
2871 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552872 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362873 req->Start();
2874 base::RunLoop().Run();
2875
jww79aceda2015-12-07 01:56:342876 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
2877 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2878 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2879 }
2880}
2881
2882// Tests that secure cookies can't be set on non-secure origins if strict secure
2883// cookies are enabled.
2884TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
2885 EmbeddedTestServer http_server;
2886 http_server.AddDefaultHandlers(
2887 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2888 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2889 https_server.AddDefaultHandlers(
2890 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2891 ASSERT_TRUE(http_server.Start());
2892 ASSERT_TRUE(https_server.Start());
2893
2894 TestExperimentalFeaturesNetworkDelegate network_delegate;
2895 TestURLRequestContext context(true);
2896 context.set_network_delegate(&network_delegate);
2897 context.Init();
2898
2899 // Try to set a Secure cookie, with experimental features enabled.
2900 {
2901 TestDelegate d;
2902 scoped_ptr<URLRequest> req(context.CreateRequest(
2903 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
2904 DEFAULT_PRIORITY, &d));
2905 req->Start();
2906 base::RunLoop().Run();
2907 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2908 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2909 }
2910
2911 // Verify that the cookie is not set.
2912 {
2913 TestDelegate d;
2914 scoped_ptr<URLRequest> req(context.CreateRequest(
2915 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2916 req->Start();
2917 base::RunLoop().Run();
2918
2919 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
2920 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2921 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2922 }
2923}
2924
2925// Tests that secure cookies can be set on secure origins even if strict secure
2926// cookies are enabled.
2927TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
2928 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2929 https_server.AddDefaultHandlers(
2930 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2931 ASSERT_TRUE(https_server.Start());
2932
2933 TestExperimentalFeaturesNetworkDelegate network_delegate;
2934 TestURLRequestContext context(true);
2935 context.set_network_delegate(&network_delegate);
2936 context.Init();
2937
2938 // Try to set a Secure cookie, with experimental features enabled.
2939 {
2940 TestDelegate d;
2941 scoped_ptr<URLRequest> req(context.CreateRequest(
2942 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
2943 DEFAULT_PRIORITY, &d));
2944 req->Start();
2945 base::RunLoop().Run();
2946 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2947 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2948 }
2949
2950 // Verify that the cookie is not set.
2951 {
2952 TestDelegate d;
2953 scoped_ptr<URLRequest> req(context.CreateRequest(
2954 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2955 req->Start();
2956 base::RunLoop().Run();
2957
2958 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362959 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2960 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2961 }
2962}
2963
mmenkefb18c772015-09-30 22:22:502964// Tests that a request is cancelled while entering suspend mode. Uses mocks
2965// rather than a spawned test server because the connection used to talk to
2966// the test server is affected by entering suspend mode on Android.
2967TEST_F(URLRequestTest, CancelOnSuspend) {
2968 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
2969 base::PowerMonitor power_monitor(make_scoped_ptr(power_monitor_source));
2970
2971 URLRequestFailedJob::AddUrlHandler();
2972
2973 TestDelegate d;
2974 // Request that just hangs.
2975 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
2976 scoped_ptr<URLRequest> r(
2977 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
2978 r->Start();
2979
2980 power_monitor_source->Suspend();
2981 // Wait for the suspend notification to cause the request to fail.
2982 base::RunLoop().Run();
2983 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
2984 EXPECT_TRUE(d.request_failed());
2985 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2986
2987 URLRequestFilter::GetInstance()->ClearHandlers();
2988
2989 // Shouldn't be needed, but just in case.
2990 power_monitor_source->Resume();
2991}
2992
[email protected]5095cd72012-11-01 10:29:162993// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2994// value for the |fixed_date| argument given to the constructor.
2995class FixedDateNetworkDelegate : public TestNetworkDelegate {
2996 public:
2997 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2998 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:202999 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163000
[email protected]cba24642014-08-15 20:49:593001 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203002 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593003 URLRequest* request,
3004 const CompletionCallback& callback,
3005 const HttpResponseHeaders* original_response_headers,
3006 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133007 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163008
3009 private:
3010 std::string fixed_date_;
3011
3012 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3013};
3014
3015int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593016 URLRequest* request,
3017 const CompletionCallback& callback,
3018 const HttpResponseHeaders* original_response_headers,
3019 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163020 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593021 HttpResponseHeaders* new_response_headers =
3022 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163023
3024 new_response_headers->RemoveHeader("Date");
3025 new_response_headers->AddHeader("Date: " + fixed_date_);
3026
3027 *override_response_headers = new_response_headers;
3028 return TestNetworkDelegate::OnHeadersReceived(request,
3029 callback,
3030 original_response_headers,
[email protected]5f714132014-03-26 10:41:163031 override_response_headers,
3032 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163033}
3034
3035// Test that cookie expiration times are adjusted for server/client clock
3036// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3037// headers by defaulting to GMT. (crbug.com/135131)
3038TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3039 LocalHttpTestServer test_server;
3040 ASSERT_TRUE(test_server.Start());
3041
3042 // Set up an expired cookie.
3043 {
3044 TestNetworkDelegate network_delegate;
3045 default_context_.set_network_delegate(&network_delegate);
3046 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193047 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193048 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553049 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363050 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193051 req->Start();
[email protected]255620da2013-08-19 13:14:293052 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163053 }
3054 // Verify that the cookie is not set.
3055 {
3056 TestNetworkDelegate network_delegate;
3057 default_context_.set_network_delegate(&network_delegate);
3058 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193059 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553060 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193061 req->Start();
[email protected]255620da2013-08-19 13:14:293062 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163063
3064 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3065 }
3066 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3067 {
3068 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3069 default_context_.set_network_delegate(&network_delegate);
3070 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193071 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193072 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553073 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363074 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193075 req->Start();
[email protected]255620da2013-08-19 13:14:293076 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163077 }
3078 // Verify that the cookie is set.
3079 {
3080 TestNetworkDelegate network_delegate;
3081 default_context_.set_network_delegate(&network_delegate);
3082 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193083 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553084 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193085 req->Start();
[email protected]255620da2013-08-19 13:14:293086 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163087
3088 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3089 }
3090}
3091
3092
[email protected]316c1e5e2012-09-12 15:17:443093// Check that it is impossible to change the referrer in the extra headers of
3094// an URLRequest.
3095TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3096 LocalHttpTestServer test_server;
3097 ASSERT_TRUE(test_server.Start());
3098
3099 // If extra headers contain referer and the request contains a referer,
3100 // only the latter shall be respected.
3101 {
3102 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193103 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553104 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193105 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443106
3107 HttpRequestHeaders headers;
3108 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193109 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443110
[email protected]f7022f32014-08-21 16:32:193111 req->Start();
[email protected]255620da2013-08-19 13:14:293112 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443113
3114 EXPECT_EQ("http://foo.com/", d.data_received());
3115 }
3116
3117 // If extra headers contain a referer but the request does not, no referer
3118 // shall be sent in the header.
3119 {
3120 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193121 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553122 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443123
3124 HttpRequestHeaders headers;
3125 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193126 req->SetExtraRequestHeaders(headers);
3127 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443128
[email protected]f7022f32014-08-21 16:32:193129 req->Start();
[email protected]255620da2013-08-19 13:14:293130 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443131
3132 EXPECT_EQ("None", d.data_received());
3133 }
3134}
3135
[email protected]b89290212009-08-14 22:37:353136class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113137 public:
mmenke9f2ec60c2015-06-01 20:59:473138 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113139
[email protected]b89290212009-08-14 22:37:353140 protected:
[email protected]21184962011-10-26 00:50:303141 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3142 // |request_method| is the method to use for the initial request.
3143 // |redirect_method| is the method that is expected to be used for the second
3144 // request, after redirection.
3145 // If |include_data| is true, data is uploaded with the request. The
3146 // response body is expected to match it exactly, if and only if
3147 // |request_method| == |redirect_method|.
3148 void HTTPRedirectMethodTest(const GURL& redirect_url,
3149 const std::string& request_method,
3150 const std::string& redirect_method,
3151 bool include_data) {
3152 static const char kData[] = "hello world";
3153 TestDelegate d;
davidben151423e2015-03-23 18:48:363154 scoped_ptr<URLRequest> req(
3155 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193156 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303157 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073158 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303159 HttpRequestHeaders headers;
3160 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513161 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543162 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193163 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303164 }
[email protected]f7022f32014-08-21 16:32:193165 req->Start();
[email protected]255620da2013-08-19 13:14:293166 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193167 EXPECT_EQ(redirect_method, req->method());
3168 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
3169 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:303170 if (include_data) {
3171 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543172 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3173 HttpRequestHeaders::kContentLength));
3174 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3175 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303176 EXPECT_EQ(kData, d.data_received());
3177 } else {
svaldez5b3a8972015-10-09 23:23:543178 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3179 HttpRequestHeaders::kContentLength));
3180 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3181 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303182 EXPECT_NE(kData, d.data_received());
3183 }
3184 }
3185 if (HasFailure())
3186 LOG(WARNING) << "Request method was: " << request_method;
3187 }
3188
jww5fe460ff2015-03-28 00:22:513189 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3190 // |request_method| is the method to use for the initial request.
3191 // |redirect_method| is the method that is expected to be used for the second
3192 // request, after redirection.
3193 // |origin_value| is the expected value for the Origin header after
3194 // redirection. If empty, expects that there will be no Origin header.
3195 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3196 const std::string& request_method,
3197 const std::string& redirect_method,
3198 const std::string& origin_value) {
3199 TestDelegate d;
3200 scoped_ptr<URLRequest> req(
3201 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3202 req->set_method(request_method);
3203 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3204 redirect_url.GetOrigin().spec(), false);
3205 req->Start();
3206
3207 base::RunLoop().Run();
3208
3209 EXPECT_EQ(redirect_method, req->method());
3210 // Note that there is no check for request success here because, for
3211 // purposes of testing, the request very well may fail. For example, if the
3212 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3213 // origin, there is not an HTTPS server in this unit test framework, so the
3214 // request would fail. However, that's fine, as long as the request headers
3215 // are in order and pass the checks below.
3216 if (origin_value.empty()) {
3217 EXPECT_FALSE(
3218 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3219 } else {
3220 std::string origin_header;
3221 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3222 HttpRequestHeaders::kOrigin, &origin_header));
3223 EXPECT_EQ(origin_value, origin_header);
3224 }
3225 }
3226
[email protected]762d2db2010-01-11 19:03:013227 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013228 const int kMsgSize = 20000; // multiple of 10
3229 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483230 char* uploadBytes = new char[kMsgSize+1];
3231 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013232 char marker = 'a';
3233 for (int idx = 0; idx < kMsgSize/10; idx++) {
3234 memcpy(ptr, "----------", 10);
3235 ptr += 10;
3236 if (idx % 100 == 0) {
3237 ptr--;
3238 *ptr++ = marker;
3239 if (++marker > 'z')
3240 marker = 'a';
3241 }
3242 }
3243 uploadBytes[kMsgSize] = '\0';
3244
[email protected]762d2db2010-01-11 19:03:013245 for (int i = 0; i < kIterations; ++i) {
3246 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193247 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553248 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193249 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013250
mmenkecbc2b712014-10-09 20:29:073251 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013252
[email protected]f7022f32014-08-21 16:32:193253 r->Start();
3254 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013255
[email protected]255620da2013-08-19 13:14:293256 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013257
[email protected]329b68b2012-11-14 17:54:273258 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:193259 << "request failed: " << r->status().status()
3260 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:013261
3262 EXPECT_FALSE(d.received_data_before_response());
3263 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013264 }
3265 delete[] uploadBytes;
3266 }
3267
[email protected]ef2bf422012-05-11 03:27:093268 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:223269 r->AppendChunkToUpload("a", 1, false);
3270 r->AppendChunkToUpload("bcd", 3, false);
3271 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
3272 r->AppendChunkToUpload("\r\n\r\n", 4, false);
3273 r->AppendChunkToUpload("0", 1, false);
3274 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:113275 }
3276
[email protected]ef2bf422012-05-11 03:27:093277 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:113278 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:273279 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:113280 "abcdthis is a longer chunk than before.\r\n\r\n02323";
3281
[email protected]329b68b2012-11-14 17:54:273282 ASSERT_EQ(1, d->response_started_count())
3283 << "request failed: " << r->status().status()
3284 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:113285
3286 EXPECT_FALSE(d->received_data_before_response());
3287
[email protected]329b68b2012-11-14 17:54:273288 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
3289 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:113290 }
3291
[email protected]ede03212012-09-07 12:52:263292 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343293 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193294 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553295 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363296 base::IntToString(num_cookies)),
3297 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343298
[email protected]f7022f32014-08-21 16:32:193299 r->Start();
3300 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343301
[email protected]255620da2013-08-19 13:14:293302 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343303
[email protected]f7022f32014-08-21 16:32:193304 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:343305
tommycli59a63432015-11-06 00:10:553306 if (!is_success)
[email protected]f7022f32014-08-21 16:32:193307 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:343308
3309 return is_success;
3310 }
3311
tommycli59a63432015-11-06 00:10:553312 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503313
tommycli59a63432015-11-06 00:10:553314 private:
[email protected]1700c6a2012-02-22 18:07:073315 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353316};
3317
tommycli59a63432015-11-06 00:10:553318namespace {
3319
3320scoped_ptr<test_server::HttpResponse> HandleRedirectConnect(
3321 const test_server::HttpRequest& request) {
3322 if (request.headers.find("Host") == request.headers.end() ||
3323 request.headers.at("Host") != "www.redirect.com" ||
3324 request.method != test_server::METHOD_CONNECT) {
3325 return nullptr;
3326 }
3327
3328 scoped_ptr<test_server::BasicHttpResponse> http_response(
3329 new test_server::BasicHttpResponse);
3330 http_response->set_code(HTTP_FOUND);
3331 http_response->AddCustomHeader("Location",
3332 "http://www.destination.com/foo.js");
3333 return http_response.Pass();
3334}
3335
3336} // namespace
3337
3338// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113339// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553340// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113341// follow.
[email protected]f2f31b32013-01-16 23:24:093342TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553343 http_test_server()->RegisterRequestHandler(
3344 base::Bind(&HandleRedirectConnect));
3345 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113346
[email protected]ceefd7fd2012-11-29 00:36:243347 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043348 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553349 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503350
[email protected]d1ec59082009-02-11 02:48:153351 TestDelegate d;
3352 {
[email protected]f7022f32014-08-21 16:32:193353 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363354 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193355 r->Start();
3356 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153357
[email protected]255620da2013-08-19 13:14:293358 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153359
[email protected]f7022f32014-08-21 16:32:193360 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153361 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193362 EXPECT_TRUE(r->proxy_server().IsEmpty());
3363 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083364 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153365 // We should not have followed the redirect.
3366 EXPECT_EQ(0, d.received_redirect_count());
3367 }
3368}
3369
[email protected]8202d0c2011-02-23 08:31:143370// This is the same as the previous test, but checks that the network delegate
3371// registers the error.
[email protected]c044616e2013-02-20 02:01:263372TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553373 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143374
[email protected]ceefd7fd2012-11-29 00:36:243375 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043376 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553377 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503378
[email protected]8202d0c2011-02-23 08:31:143379 TestDelegate d;
3380 {
[email protected]f7022f32014-08-21 16:32:193381 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363382 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193383 r->Start();
3384 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143385
[email protected]255620da2013-08-19 13:14:293386 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143387
[email protected]f7022f32014-08-21 16:32:193388 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153389 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193390 EXPECT_TRUE(r->proxy_server().IsEmpty());
3391 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143392 EXPECT_EQ(1, d.response_started_count());
3393 // We should not have followed the redirect.
3394 EXPECT_EQ(0, d.received_redirect_count());
3395
3396 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053397 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143398 }
3399}
3400
[email protected]dc5a5cf2012-09-26 02:49:303401// Tests that we can block and asynchronously return OK in various stages.
3402TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3403 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3404 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3405 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3406 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3407 };
3408 static const size_t blocking_stages_length = arraysize(blocking_stages);
3409
tommycli59a63432015-11-06 00:10:553410 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:303411
3412 TestDelegate d;
3413 BlockingNetworkDelegate network_delegate(
3414 BlockingNetworkDelegate::USER_CALLBACK);
3415 network_delegate.set_block_on(
3416 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3417 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3418 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3419
3420 TestURLRequestContext context(true);
3421 context.set_network_delegate(&network_delegate);
3422 context.Init();
3423
3424 {
[email protected]f7022f32014-08-21 16:32:193425 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553426 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303427
[email protected]f7022f32014-08-21 16:32:193428 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303429 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293430 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303431 EXPECT_EQ(blocking_stages[i],
3432 network_delegate.stage_blocked_for_callback());
3433 network_delegate.DoCallback(OK);
3434 }
[email protected]255620da2013-08-19 13:14:293435 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193436 EXPECT_EQ(200, r->GetResponseCode());
3437 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303438 EXPECT_EQ(1, network_delegate.created_requests());
3439 EXPECT_EQ(0, network_delegate.destroyed_requests());
3440 }
3441 EXPECT_EQ(1, network_delegate.destroyed_requests());
3442}
3443
[email protected]4c76d7c2011-04-15 19:14:123444// Tests that the network delegate can block and cancel a request.
3445TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:553446 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123447
3448 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303449 BlockingNetworkDelegate network_delegate(
3450 BlockingNetworkDelegate::AUTO_CALLBACK);
3451 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3452 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123453
[email protected]d5a4dd62012-05-23 01:41:043454 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553455 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503456
[email protected]4c76d7c2011-04-15 19:14:123457 {
[email protected]f7022f32014-08-21 16:32:193458 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553459 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123460
[email protected]f7022f32014-08-21 16:32:193461 r->Start();
[email protected]255620da2013-08-19 13:14:293462 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123463
[email protected]f7022f32014-08-21 16:32:193464 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153465 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193466 EXPECT_TRUE(r->proxy_server().IsEmpty());
3467 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123468 EXPECT_EQ(1, network_delegate.created_requests());
3469 EXPECT_EQ(0, network_delegate.destroyed_requests());
3470 }
3471 EXPECT_EQ(1, network_delegate.destroyed_requests());
3472}
3473
[email protected]b4438d32012-09-27 06:15:303474// Helper function for NetworkDelegateCancelRequestAsynchronously and
3475// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3476// delegate operating in |block_mode| and a request for |url|. It blocks the
3477// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3478void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3479 BlockingNetworkDelegate::Stage stage,
3480 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363481 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303482 BlockingNetworkDelegate network_delegate(block_mode);
3483 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3484 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363485
[email protected]b4438d32012-09-27 06:15:303486 TestURLRequestContext context(true);
3487 context.set_network_delegate(&network_delegate);
3488 context.Init();
[email protected]3cd384c602011-08-31 16:12:363489
3490 {
davidben151423e2015-03-23 18:48:363491 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363492
[email protected]f7022f32014-08-21 16:32:193493 r->Start();
[email protected]255620da2013-08-19 13:14:293494 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363495
[email protected]f7022f32014-08-21 16:32:193496 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153497 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193498 EXPECT_TRUE(r->proxy_server().IsEmpty());
3499 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363500 EXPECT_EQ(1, network_delegate.created_requests());
3501 EXPECT_EQ(0, network_delegate.destroyed_requests());
3502 }
3503 EXPECT_EQ(1, network_delegate.destroyed_requests());
3504}
3505
[email protected]b4438d32012-09-27 06:15:303506// The following 3 tests check that the network delegate can cancel a request
3507// synchronously in various stages of the request.
3508TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:553509 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303510 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3511 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553512 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303513}
3514
3515TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:553516 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303517 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3518 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553519 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303520}
3521
3522TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:553523 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303524 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3525 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553526 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303527}
3528
3529// The following 3 tests check that the network delegate can cancel a request
3530// asynchronously in various stages of the request.
3531TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:553532 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303533 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3534 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553535 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303536}
3537
3538TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:553539 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303540 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3541 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553542 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303543}
3544
3545TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:553546 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303547 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3548 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553549 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303550}
3551
[email protected]4c76d7c2011-04-15 19:14:123552// Tests that the network delegate can block and redirect a request to a new
3553// URL.
3554TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:553555 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123556
3557 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303558 BlockingNetworkDelegate network_delegate(
3559 BlockingNetworkDelegate::AUTO_CALLBACK);
3560 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553561 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:123562 network_delegate.set_redirect_url(redirect_url);
3563
[email protected]d5a4dd62012-05-23 01:41:043564 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553565 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503566
[email protected]4c76d7c2011-04-15 19:14:123567 {
tommycli59a63432015-11-06 00:10:553568 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363569 scoped_ptr<URLRequest> r(
3570 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123571
[email protected]6be6fa92014-08-06 23:44:563572 // Quit after hitting the redirect, so can check the headers.
3573 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193574 r->Start();
[email protected]255620da2013-08-19 13:14:293575 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123576
[email protected]6be6fa92014-08-06 23:44:563577 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193578 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3579 EXPECT_EQ(307, r->GetResponseCode());
3580 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563581 std::string location;
[email protected]f7022f32014-08-21 16:32:193582 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3583 &location));
[email protected]6be6fa92014-08-06 23:44:563584 EXPECT_EQ(redirect_url, GURL(location));
3585
3586 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193587 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563588 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193589 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553590 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273591 EXPECT_EQ(
3592 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553593 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3594 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273595
[email protected]f7022f32014-08-21 16:32:193596 EXPECT_EQ(0, r->status().error());
3597 EXPECT_EQ(redirect_url, r->url());
3598 EXPECT_EQ(original_url, r->original_url());
3599 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123600 EXPECT_EQ(1, network_delegate.created_requests());
3601 EXPECT_EQ(0, network_delegate.destroyed_requests());
3602 }
3603 EXPECT_EQ(1, network_delegate.destroyed_requests());
3604}
3605
[email protected]b813ed72012-04-05 08:21:363606// Tests that the network delegate can block and redirect a request to a new
3607// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3608TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:553609 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:363610
3611 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303612 BlockingNetworkDelegate network_delegate(
3613 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:553614 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:363615 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363616
[email protected]d5a4dd62012-05-23 01:41:043617 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553618 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363619
3620 {
tommycli59a63432015-11-06 00:10:553621 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363622 scoped_ptr<URLRequest> r(
3623 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363624
[email protected]6be6fa92014-08-06 23:44:563625 // Quit after hitting the redirect, so can check the headers.
3626 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193627 r->Start();
[email protected]255620da2013-08-19 13:14:293628 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363629
[email protected]6be6fa92014-08-06 23:44:563630 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193631 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3632 EXPECT_EQ(307, r->GetResponseCode());
3633 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563634 std::string location;
[email protected]f7022f32014-08-21 16:32:193635 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3636 &location));
[email protected]6be6fa92014-08-06 23:44:563637 EXPECT_EQ(redirect_url, GURL(location));
3638
3639 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193640 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563641 base::RunLoop().Run();
3642
[email protected]f7022f32014-08-21 16:32:193643 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553644 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273645 EXPECT_EQ(
3646 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553647 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3648 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193649 EXPECT_EQ(0, r->status().error());
3650 EXPECT_EQ(redirect_url, r->url());
3651 EXPECT_EQ(original_url, r->original_url());
3652 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363653 EXPECT_EQ(1, network_delegate.created_requests());
3654 EXPECT_EQ(0, network_delegate.destroyed_requests());
3655 }
3656 EXPECT_EQ(1, network_delegate.destroyed_requests());
3657}
3658
[email protected]3c5ca8c2011-09-29 01:14:513659// Tests that redirects caused by the network delegate preserve POST data.
3660TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:553661 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:513662
3663 const char kData[] = "hello world";
3664
3665 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303666 BlockingNetworkDelegate network_delegate(
3667 BlockingNetworkDelegate::AUTO_CALLBACK);
3668 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553669 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:513670 network_delegate.set_redirect_url(redirect_url);
3671
[email protected]ef2bf422012-05-11 03:27:093672 TestURLRequestContext context(true);
3673 context.set_network_delegate(&network_delegate);
3674 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513675
3676 {
tommycli59a63432015-11-06 00:10:553677 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363678 scoped_ptr<URLRequest> r(
3679 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193680 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073681 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513682 HttpRequestHeaders headers;
3683 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513684 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193685 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563686
3687 // Quit after hitting the redirect, so can check the headers.
3688 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193689 r->Start();
[email protected]255620da2013-08-19 13:14:293690 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513691
[email protected]6be6fa92014-08-06 23:44:563692 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193693 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3694 EXPECT_EQ(307, r->GetResponseCode());
3695 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563696 std::string location;
[email protected]f7022f32014-08-21 16:32:193697 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3698 &location));
[email protected]6be6fa92014-08-06 23:44:563699 EXPECT_EQ(redirect_url, GURL(location));
3700
3701 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193702 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563703 base::RunLoop().Run();
3704
[email protected]f7022f32014-08-21 16:32:193705 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3706 EXPECT_EQ(0, r->status().error());
3707 EXPECT_EQ(redirect_url, r->url());
3708 EXPECT_EQ(original_url, r->original_url());
3709 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513710 EXPECT_EQ(1, network_delegate.created_requests());
3711 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193712 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513713 EXPECT_EQ(kData, d.data_received());
3714 }
3715 EXPECT_EQ(1, network_delegate.destroyed_requests());
3716}
3717
[email protected]5f714132014-03-26 10:41:163718// Tests that the network delegate can block and redirect a request to a new
3719// URL during OnHeadersReceived.
3720TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:553721 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:163722
3723 TestDelegate d;
3724 BlockingNetworkDelegate network_delegate(
3725 BlockingNetworkDelegate::AUTO_CALLBACK);
3726 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:553727 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:163728 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3729
3730 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553731 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:163732
3733 {
tommycli59a63432015-11-06 00:10:553734 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363735 scoped_ptr<URLRequest> r(
3736 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163737
[email protected]f7022f32014-08-21 16:32:193738 r->Start();
[email protected]5f714132014-03-26 10:41:163739 base::RunLoop().Run();
3740
[email protected]f7022f32014-08-21 16:32:193741 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553742 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273743 EXPECT_EQ(
3744 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553745 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3746 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193747
3748 EXPECT_EQ(OK, r->status().error());
3749 EXPECT_EQ(redirect_url, r->url());
3750 EXPECT_EQ(original_url, r->original_url());
3751 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163752 EXPECT_EQ(2, network_delegate.created_requests());
3753 EXPECT_EQ(0, network_delegate.destroyed_requests());
3754 }
3755 EXPECT_EQ(1, network_delegate.destroyed_requests());
3756}
3757
[email protected]c2911d72011-10-03 22:16:363758// Tests that the network delegate can synchronously complete OnAuthRequired
3759// by taking no action. This indicates that the NetworkDelegate does not want to
3760// handle the challenge, and is passing the buck along to the
3761// URLRequest::Delegate.
3762TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:553763 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363764
3765 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303766 BlockingNetworkDelegate network_delegate(
3767 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363768
[email protected]ef2bf422012-05-11 03:27:093769 TestURLRequestContext context(true);
3770 context.set_network_delegate(&network_delegate);
3771 context.Init();
[email protected]c2911d72011-10-03 22:16:363772
[email protected]f3cf9802011-10-28 18:44:583773 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363774
3775 {
tommycli59a63432015-11-06 00:10:553776 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363777 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193778 r->Start();
[email protected]79e1fd62013-06-20 06:50:043779
[email protected]255620da2013-08-19 13:14:293780 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043781
[email protected]f7022f32014-08-21 16:32:193782 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3783 EXPECT_EQ(0, r->status().error());
3784 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043785 EXPECT_TRUE(d.auth_required_called());
3786 EXPECT_EQ(1, network_delegate.created_requests());
3787 EXPECT_EQ(0, network_delegate.destroyed_requests());
3788 }
3789 EXPECT_EQ(1, network_delegate.destroyed_requests());
3790}
3791
3792TEST_F(URLRequestTestHTTP,
3793 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:553794 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:043795
3796 TestDelegate d;
3797 BlockingNetworkDelegate network_delegate(
3798 BlockingNetworkDelegate::SYNCHRONOUS);
3799
3800 TestURLRequestContext context(true);
3801 context.set_network_delegate(&network_delegate);
3802 context.Init();
3803
3804 d.set_credentials(AuthCredentials(kUser, kSecret));
3805
3806 {
tommycli59a63432015-11-06 00:10:553807 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363808 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193809 r->Start();
[email protected]79e1fd62013-06-20 06:50:043810
3811 {
3812 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193813 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043814 EXPECT_FALSE(headers.HasHeader("Authorization"));
3815 }
3816
[email protected]255620da2013-08-19 13:14:293817 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363818
[email protected]f7022f32014-08-21 16:32:193819 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3820 EXPECT_EQ(0, r->status().error());
3821 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363822 EXPECT_TRUE(d.auth_required_called());
3823 EXPECT_EQ(1, network_delegate.created_requests());
3824 EXPECT_EQ(0, network_delegate.destroyed_requests());
3825 }
3826 EXPECT_EQ(1, network_delegate.destroyed_requests());
3827}
3828
3829// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403830// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363831TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:553832 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363833
3834 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303835 BlockingNetworkDelegate network_delegate(
3836 BlockingNetworkDelegate::SYNCHRONOUS);
3837 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363838 network_delegate.set_auth_retval(
3839 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3840
[email protected]f3cf9802011-10-28 18:44:583841 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363842
[email protected]ef2bf422012-05-11 03:27:093843 TestURLRequestContext context(true);
3844 context.set_network_delegate(&network_delegate);
3845 context.Init();
[email protected]c2911d72011-10-03 22:16:363846
3847 {
tommycli59a63432015-11-06 00:10:553848 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363849 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193850 r->Start();
[email protected]255620da2013-08-19 13:14:293851 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363852
[email protected]f7022f32014-08-21 16:32:193853 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3854 EXPECT_EQ(0, r->status().error());
3855 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363856 EXPECT_FALSE(d.auth_required_called());
3857 EXPECT_EQ(1, network_delegate.created_requests());
3858 EXPECT_EQ(0, network_delegate.destroyed_requests());
3859 }
3860 EXPECT_EQ(1, network_delegate.destroyed_requests());
3861}
3862
[email protected]79e1fd62013-06-20 06:50:043863// Same as above, but also tests that GetFullRequestHeaders returns the proper
3864// headers (for the first or second request) when called at the proper times.
3865TEST_F(URLRequestTestHTTP,
3866 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:553867 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:043868
3869 TestDelegate d;
3870 BlockingNetworkDelegate network_delegate(
3871 BlockingNetworkDelegate::SYNCHRONOUS);
3872 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3873 network_delegate.set_auth_retval(
3874 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3875
3876 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3877
3878 TestURLRequestContext context(true);
3879 context.set_network_delegate(&network_delegate);
3880 context.Init();
3881
3882 {
tommycli59a63432015-11-06 00:10:553883 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363884 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193885 r->Start();
[email protected]255620da2013-08-19 13:14:293886 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043887
[email protected]f7022f32014-08-21 16:32:193888 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3889 EXPECT_EQ(0, r->status().error());
3890 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043891 EXPECT_FALSE(d.auth_required_called());
3892 EXPECT_EQ(1, network_delegate.created_requests());
3893 EXPECT_EQ(0, network_delegate.destroyed_requests());
3894
3895 {
3896 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193897 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043898 EXPECT_TRUE(headers.HasHeader("Authorization"));
3899 }
3900 }
3901 EXPECT_EQ(1, network_delegate.destroyed_requests());
3902}
3903
[email protected]c2911d72011-10-03 22:16:363904// Tests that the network delegate can synchronously complete OnAuthRequired
3905// by cancelling authentication.
3906TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:553907 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363908
3909 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303910 BlockingNetworkDelegate network_delegate(
3911 BlockingNetworkDelegate::SYNCHRONOUS);
3912 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363913 network_delegate.set_auth_retval(
3914 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3915
[email protected]ef2bf422012-05-11 03:27:093916 TestURLRequestContext context(true);
3917 context.set_network_delegate(&network_delegate);
3918 context.Init();
[email protected]c2911d72011-10-03 22:16:363919
3920 {
tommycli59a63432015-11-06 00:10:553921 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363922 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193923 r->Start();
[email protected]255620da2013-08-19 13:14:293924 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363925
[email protected]f7022f32014-08-21 16:32:193926 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3927 EXPECT_EQ(OK, r->status().error());
3928 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363929 EXPECT_FALSE(d.auth_required_called());
3930 EXPECT_EQ(1, network_delegate.created_requests());
3931 EXPECT_EQ(0, network_delegate.destroyed_requests());
3932 }
3933 EXPECT_EQ(1, network_delegate.destroyed_requests());
3934}
3935
3936// Tests that the network delegate can asynchronously complete OnAuthRequired
3937// by taking no action. This indicates that the NetworkDelegate does not want
3938// to handle the challenge, and is passing the buck along to the
3939// URLRequest::Delegate.
3940TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:553941 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363942
3943 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303944 BlockingNetworkDelegate network_delegate(
3945 BlockingNetworkDelegate::AUTO_CALLBACK);
3946 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363947
[email protected]ef2bf422012-05-11 03:27:093948 TestURLRequestContext context(true);
3949 context.set_network_delegate(&network_delegate);
3950 context.Init();
[email protected]c2911d72011-10-03 22:16:363951
[email protected]f3cf9802011-10-28 18:44:583952 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363953
3954 {
tommycli59a63432015-11-06 00:10:553955 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363956 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193957 r->Start();
[email protected]255620da2013-08-19 13:14:293958 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363959
[email protected]f7022f32014-08-21 16:32:193960 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3961 EXPECT_EQ(0, r->status().error());
3962 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363963 EXPECT_TRUE(d.auth_required_called());
3964 EXPECT_EQ(1, network_delegate.created_requests());
3965 EXPECT_EQ(0, network_delegate.destroyed_requests());
3966 }
3967 EXPECT_EQ(1, network_delegate.destroyed_requests());
3968}
3969
3970// Tests that the network delegate can asynchronously complete OnAuthRequired
3971// by setting credentials.
3972TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:553973 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363974
3975 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303976 BlockingNetworkDelegate network_delegate(
3977 BlockingNetworkDelegate::AUTO_CALLBACK);
3978 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363979 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363980 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3981
[email protected]f3cf9802011-10-28 18:44:583982 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363983 network_delegate.set_auth_credentials(auth_credentials);
3984
[email protected]ef2bf422012-05-11 03:27:093985 TestURLRequestContext context(true);
3986 context.set_network_delegate(&network_delegate);
3987 context.Init();
[email protected]c2911d72011-10-03 22:16:363988
3989 {
tommycli59a63432015-11-06 00:10:553990 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363991 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193992 r->Start();
[email protected]255620da2013-08-19 13:14:293993 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363994
[email protected]f7022f32014-08-21 16:32:193995 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3996 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:363997
[email protected]f7022f32014-08-21 16:32:193998 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363999 EXPECT_FALSE(d.auth_required_called());
4000 EXPECT_EQ(1, network_delegate.created_requests());
4001 EXPECT_EQ(0, network_delegate.destroyed_requests());
4002 }
4003 EXPECT_EQ(1, network_delegate.destroyed_requests());
4004}
4005
4006// Tests that the network delegate can asynchronously complete OnAuthRequired
4007// by cancelling authentication.
4008TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554009 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364010
4011 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304012 BlockingNetworkDelegate network_delegate(
4013 BlockingNetworkDelegate::AUTO_CALLBACK);
4014 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364015 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364016 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4017
[email protected]ef2bf422012-05-11 03:27:094018 TestURLRequestContext context(true);
4019 context.set_network_delegate(&network_delegate);
4020 context.Init();
[email protected]c2911d72011-10-03 22:16:364021
4022 {
tommycli59a63432015-11-06 00:10:554023 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364024 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194025 r->Start();
[email protected]255620da2013-08-19 13:14:294026 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364027
[email protected]f7022f32014-08-21 16:32:194028 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4029 EXPECT_EQ(OK, r->status().error());
4030 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364031 EXPECT_FALSE(d.auth_required_called());
4032 EXPECT_EQ(1, network_delegate.created_requests());
4033 EXPECT_EQ(0, network_delegate.destroyed_requests());
4034 }
4035 EXPECT_EQ(1, network_delegate.destroyed_requests());
4036}
4037
[email protected]9045b8822012-01-13 20:35:354038// Tests that we can handle when a network request was canceled while we were
4039// waiting for the network delegate.
4040// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4041TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554042 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354043
4044 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304045 BlockingNetworkDelegate network_delegate(
4046 BlockingNetworkDelegate::USER_CALLBACK);
4047 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354048
[email protected]ef2bf422012-05-11 03:27:094049 TestURLRequestContext context(true);
4050 context.set_network_delegate(&network_delegate);
4051 context.Init();
[email protected]9045b8822012-01-13 20:35:354052
4053 {
[email protected]f7022f32014-08-21 16:32:194054 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554055 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354056
[email protected]f7022f32014-08-21 16:32:194057 r->Start();
[email protected]255620da2013-08-19 13:14:294058 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304059 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4060 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354061 EXPECT_EQ(0, network_delegate.completed_requests());
4062 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194063 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354064 // Ensure that network delegate is notified.
4065 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194066 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4067 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354068 EXPECT_EQ(1, network_delegate.created_requests());
4069 EXPECT_EQ(0, network_delegate.destroyed_requests());
4070 }
4071 EXPECT_EQ(1, network_delegate.destroyed_requests());
4072}
4073
4074// Tests that we can handle when a network request was canceled while we were
4075// waiting for the network delegate.
4076// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
4077TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554078 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354079
4080 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304081 BlockingNetworkDelegate network_delegate(
4082 BlockingNetworkDelegate::USER_CALLBACK);
4083 network_delegate.set_block_on(
4084 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354085
[email protected]ef2bf422012-05-11 03:27:094086 TestURLRequestContext context(true);
4087 context.set_network_delegate(&network_delegate);
4088 context.Init();
[email protected]9045b8822012-01-13 20:35:354089
4090 {
[email protected]f7022f32014-08-21 16:32:194091 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554092 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354093
[email protected]f7022f32014-08-21 16:32:194094 r->Start();
[email protected]255620da2013-08-19 13:14:294095 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304096 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4097 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354098 EXPECT_EQ(0, network_delegate.completed_requests());
4099 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194100 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354101 // Ensure that network delegate is notified.
4102 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194103 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4104 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354105 EXPECT_EQ(1, network_delegate.created_requests());
4106 EXPECT_EQ(0, network_delegate.destroyed_requests());
4107 }
4108 EXPECT_EQ(1, network_delegate.destroyed_requests());
4109}
4110
4111// Tests that we can handle when a network request was canceled while we were
4112// waiting for the network delegate.
4113// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4114TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554115 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354116
4117 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304118 BlockingNetworkDelegate network_delegate(
4119 BlockingNetworkDelegate::USER_CALLBACK);
4120 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354121
[email protected]ef2bf422012-05-11 03:27:094122 TestURLRequestContext context(true);
4123 context.set_network_delegate(&network_delegate);
4124 context.Init();
[email protected]9045b8822012-01-13 20:35:354125
4126 {
[email protected]f7022f32014-08-21 16:32:194127 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554128 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354129
[email protected]f7022f32014-08-21 16:32:194130 r->Start();
[email protected]255620da2013-08-19 13:14:294131 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304132 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4133 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354134 EXPECT_EQ(0, network_delegate.completed_requests());
4135 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194136 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354137 // Ensure that network delegate is notified.
4138 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194139 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4140 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354141 EXPECT_EQ(1, network_delegate.created_requests());
4142 EXPECT_EQ(0, network_delegate.destroyed_requests());
4143 }
4144 EXPECT_EQ(1, network_delegate.destroyed_requests());
4145}
4146
4147// Tests that we can handle when a network request was canceled while we were
4148// waiting for the network delegate.
4149// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024150TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554151 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354152
4153 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304154 BlockingNetworkDelegate network_delegate(
4155 BlockingNetworkDelegate::USER_CALLBACK);
4156 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354157
[email protected]ef2bf422012-05-11 03:27:094158 TestURLRequestContext context(true);
4159 context.set_network_delegate(&network_delegate);
4160 context.Init();
[email protected]9045b8822012-01-13 20:35:354161
4162 {
[email protected]f7022f32014-08-21 16:32:194163 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554164 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354165
[email protected]f7022f32014-08-21 16:32:194166 r->Start();
[email protected]255620da2013-08-19 13:14:294167 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304168 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4169 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354170 EXPECT_EQ(0, network_delegate.completed_requests());
4171 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194172 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354173 // Ensure that network delegate is notified.
4174 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194175 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4176 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354177 EXPECT_EQ(1, network_delegate.created_requests());
4178 EXPECT_EQ(0, network_delegate.destroyed_requests());
4179 }
4180 EXPECT_EQ(1, network_delegate.destroyed_requests());
4181}
4182
tommycli59a63432015-11-06 00:10:554183namespace {
4184
4185scoped_ptr<test_server::HttpResponse> HandleServerAuthConnect(
4186 const test_server::HttpRequest& request) {
4187 if (request.headers.find("Host") == request.headers.end() ||
4188 request.headers.at("Host") != "www.server-auth.com" ||
4189 request.method != test_server::METHOD_CONNECT) {
4190 return nullptr;
4191 }
4192
4193 scoped_ptr<test_server::BasicHttpResponse> http_response(
4194 new test_server::BasicHttpResponse);
4195 http_response->set_code(HTTP_UNAUTHORIZED);
4196 http_response->AddCustomHeader("WWW-Authenticate",
4197 "Basic realm=\"WallyWorld\"");
4198 return http_response.Pass();
4199}
4200
4201} // namespace
4202
4203// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114204// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554205// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354206TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554207 http_test_server()->RegisterRequestHandler(
4208 base::Bind(&HandleServerAuthConnect));
4209 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114210
[email protected]ceefd7fd2012-11-29 00:36:244211 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044212 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554213 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504214
[email protected]dc651782009-02-14 01:45:084215 TestDelegate d;
4216 {
[email protected]f7022f32014-08-21 16:32:194217 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364218 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084219
[email protected]f7022f32014-08-21 16:32:194220 r->Start();
4221 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084222
[email protected]255620da2013-08-19 13:14:294223 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084224
[email protected]f7022f32014-08-21 16:32:194225 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:154226 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:194227 EXPECT_TRUE(r->proxy_server().IsEmpty());
4228 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:084229 }
4230}
4231
[email protected]b89290212009-08-14 22:37:354232TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554233 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114234
initial.commit586acc5fe2008-07-26 22:42:524235 TestDelegate d;
4236 {
[email protected]f7022f32014-08-21 16:32:194237 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554238 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524239
[email protected]f7022f32014-08-21 16:32:194240 r->Start();
4241 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524242
[email protected]255620da2013-08-19 13:14:294243 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524244
4245 EXPECT_EQ(1, d.response_started_count());
4246 EXPECT_FALSE(d.received_data_before_response());
4247 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554248 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194249 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554250 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194251 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164252
[email protected]9e743cd2010-03-16 07:03:534253 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524254 }
initial.commit586acc5fe2008-07-26 22:42:524255}
4256
[email protected]263163f2012-06-14 22:40:344257// This test has the server send a large number of cookies to the client.
4258// To ensure that no number of cookies causes a crash, a galloping binary
4259// search is used to estimate that maximum number of cookies that are accepted
4260// by the browser. Beyond the maximum number, the request will fail with
4261// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304262#if defined(OS_WIN)
4263// http://crbug.com/177916
4264#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4265#else
4266#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4267#endif // defined(OS_WIN)
4268TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554269 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344270
4271 int lower_bound = 0;
4272 int upper_bound = 1;
4273
4274 // Double the number of cookies until the response header limits are
4275 // exceeded.
4276 while (DoManyCookiesRequest(upper_bound)) {
4277 lower_bound = upper_bound;
4278 upper_bound *= 2;
4279 ASSERT_LT(upper_bound, 1000000);
4280 }
4281
pkasting6b68a162014-12-01 22:10:294282 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344283 if (tolerance < 2)
4284 tolerance = 2;
4285
4286 // Perform a binary search to find the highest possible number of cookies,
4287 // within the desired tolerance.
4288 while (upper_bound - lower_bound >= tolerance) {
4289 int num_cookies = (lower_bound + upper_bound) / 2;
4290
4291 if (DoManyCookiesRequest(num_cookies))
4292 lower_bound = num_cookies;
4293 else
4294 upper_bound = num_cookies;
4295 }
4296 // Success: the test did not crash.
4297}
4298
[email protected]b89290212009-08-14 22:37:354299TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554300 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114301
initial.commit586acc5fe2008-07-26 22:42:524302 TestDelegate d;
4303 {
[email protected]f7022f32014-08-21 16:32:194304 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554305 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524306
[email protected]f7022f32014-08-21 16:32:194307 r->Start();
4308 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524309
[email protected]255620da2013-08-19 13:14:294310 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524311
4312 EXPECT_EQ(1, d.response_started_count());
4313 EXPECT_FALSE(d.received_data_before_response());
4314 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554315 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194316 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554317 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194318 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524319 }
[email protected]5d7b373e2009-09-02 07:19:034320}
4321
[email protected]79e1fd62013-06-20 06:50:044322TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554323 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044324
4325 TestDelegate d;
4326 {
tommycli59a63432015-11-06 00:10:554327 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:364328 scoped_ptr<URLRequest> r(
4329 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044330
4331 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194332 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044333
[email protected]f7022f32014-08-21 16:32:194334 r->Start();
4335 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044336
[email protected]255620da2013-08-19 13:14:294337 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044338
4339 EXPECT_EQ(1, d.response_started_count());
4340 EXPECT_FALSE(d.received_data_before_response());
4341 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554342 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194343 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554344 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194345 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044346
4347 EXPECT_TRUE(d.have_full_request_headers());
4348 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4349 }
4350}
4351
[email protected]58e32bb2013-01-21 18:23:254352TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554353 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254354
4355 TestDelegate d;
4356 {
[email protected]f7022f32014-08-21 16:32:194357 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554358 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254359
[email protected]f7022f32014-08-21 16:32:194360 r->Start();
4361 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254362
[email protected]255620da2013-08-19 13:14:294363 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254364
4365 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194366 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254367 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4368
4369 EXPECT_EQ(1, d.response_started_count());
4370 EXPECT_FALSE(d.received_data_before_response());
4371 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554372 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194373 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554374 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194375 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254376 }
4377}
4378
tommycli59a63432015-11-06 00:10:554379// TODO(svaldez): Update tests to use EmbeddedTestServer.
4380#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394381TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:554382 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
4383 SpawnedTestServer::kLocalhost,
4384 base::FilePath(kTestFilePath));
4385
4386 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:394387
4388 // Parameter that specifies the Content-Length field in the response:
4389 // C - Compressed length.
4390 // U - Uncompressed length.
4391 // L - Large length (larger than both C & U).
4392 // M - Medium length (between C & U).
4393 // S - Small length (smaller than both C & U).
4394 const char test_parameters[] = "CULMS";
4395 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4396 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444397 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394398 // S has too little data, but we seem to accept it.
4399 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374400 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394401
4402 for (int i = 0; i < num_tests ; i++) {
4403 TestDelegate d;
4404 {
tommycli59a63432015-11-06 00:10:554405 std::string test_file = base::StringPrintf(
4406 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394407
[email protected]ceefd7fd2012-11-29 00:36:244408 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094409 TestURLRequestContext context(true);
4410 context.set_network_delegate(&network_delegate);
4411 context.Init();
[email protected]87a09a92011-07-14 15:50:504412
[email protected]f7022f32014-08-21 16:32:194413 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554414 test_server.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194415 r->Start();
4416 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394417
[email protected]255620da2013-08-19 13:14:294418 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394419
4420 EXPECT_EQ(1, d.response_started_count());
4421 EXPECT_FALSE(d.received_data_before_response());
4422 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194423 << " status = " << r->status().status()
4424 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394425 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194426 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394427 << " Parameter = \"" << test_file << "\"";
4428 } else {
[email protected]f7022f32014-08-21 16:32:194429 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4430 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394431 << " Parameter = \"" << test_file << "\"";
4432 }
4433 }
4434 }
4435}
tommycli59a63432015-11-06 00:10:554436#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394437
tbansala1caf9612015-06-01 20:24:184438TEST_F(URLRequestTestHTTP, NetworkQualityEstimator) {
tommycli59a63432015-11-06 00:10:554439 ASSERT_TRUE(http_test_server()->Start());
tbansalea2fb8c2015-05-22 22:23:004440 // Enable requests to local host to be used for network quality estimation.
tbansalb177b5392015-06-25 11:13:024441 std::map<std::string, std::string> variation_params;
tbansal1c92d5b2015-08-14 20:14:434442 NetworkQualityEstimator estimator(scoped_ptr<net::ExternalEstimateProvider>(),
4443 variation_params, true, true);
tbansalea2fb8c2015-05-22 22:23:004444
4445 TestDelegate d;
4446 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4447 TestURLRequestContext context(true);
4448 context.set_network_quality_estimator(&estimator);
4449 context.set_network_delegate(&network_delegate);
4450 context.Init();
4451
tommycli59a63432015-11-06 00:10:554452 std::string url = "/defaultresponse";
tbansalea2fb8c2015-05-22 22:23:004453
tommycli59a63432015-11-06 00:10:554454 scoped_ptr<URLRequest> r(context.CreateRequest(
4455 http_test_server()->GetURL(url), DEFAULT_PRIORITY, &d));
tbansalea2fb8c2015-05-22 22:23:004456 r->Start();
4457
4458 base::RunLoop().Run();
4459
tbansal9533b6f2015-08-11 22:06:084460 base::TimeDelta rtt;
4461 int32_t kbps;
4462 EXPECT_TRUE(estimator.GetRTTEstimate(&rtt));
4463 EXPECT_TRUE(estimator.GetDownlinkThroughputKbpsEstimate(&kbps));
4464 EXPECT_GE(rtt, base::TimeDelta());
4465 EXPECT_LT(rtt, base::TimeDelta::Max());
4466 EXPECT_GT(kbps, 0);
tbansalea2fb8c2015-05-22 22:23:004467
4468 // Verify that histograms are not populated. They should populate only when
4469 // there is a change in ConnectionType.
4470 base::HistogramTester histogram_tester;
4471 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 0);
4472 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 0);
4473
4474 NetworkChangeNotifier::NotifyObserversOfConnectionTypeChangeForTests(
4475 NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI);
4476 base::MessageLoop::current()->RunUntilIdle();
4477 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 1);
4478 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 1);
4479}
4480
[email protected]58e32bb2013-01-21 18:23:254481TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:554482 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254483
tommycli59a63432015-11-06 00:10:554484 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454485 GURL original_url =
tommycli59a63432015-11-06 00:10:554486 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254487 TestDelegate d;
davidben151423e2015-03-23 18:48:364488 scoped_ptr<URLRequest> req(
4489 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194490 req->Start();
[email protected]255620da2013-08-19 13:14:294491 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254492
4493 EXPECT_EQ(1, d.response_started_count());
4494 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194495 EXPECT_EQ(destination_url, req->url());
4496 EXPECT_EQ(original_url, req->original_url());
4497 ASSERT_EQ(2U, req->url_chain().size());
4498 EXPECT_EQ(original_url, req->url_chain()[0]);
4499 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254500
4501 LoadTimingInfo load_timing_info_before_redirect;
4502 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4503 &load_timing_info_before_redirect));
4504 TestLoadTimingNotReused(load_timing_info_before_redirect,
4505 CONNECT_TIMING_HAS_DNS_TIMES);
4506
4507 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194508 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254509 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4510
4511 // Check that a new socket was used on redirect, since the server does not
4512 // supposed keep-alive sockets, and that the times before the redirect are
4513 // before the ones recorded for the second request.
4514 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4515 load_timing_info.socket_log_id);
4516 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4517 load_timing_info.connect_timing.connect_start);
4518}
4519
[email protected]8f1ac082011-04-19 21:14:134520TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:554521 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:134522
tommycli59a63432015-11-06 00:10:554523 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454524 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:554525 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
4526 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
4527 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:134528 TestDelegate d;
davidben151423e2015-03-23 18:48:364529 scoped_ptr<URLRequest> req(
4530 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194531 req->Start();
[email protected]255620da2013-08-19 13:14:294532 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134533
4534 EXPECT_EQ(1, d.response_started_count());
4535 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194536 EXPECT_EQ(destination_url, req->url());
4537 EXPECT_EQ(original_url, req->original_url());
4538 ASSERT_EQ(3U, req->url_chain().size());
4539 EXPECT_EQ(original_url, req->url_chain()[0]);
4540 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4541 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134542}
4543
[email protected]abe1c4a2013-10-25 19:28:514544// First and second pieces of information logged by delegates to URLRequests.
4545const char kFirstDelegateInfo[] = "Wonderful delegate";
4546const char kSecondDelegateInfo[] = "Exciting delegate";
4547
4548// Logs delegate information to a URLRequest. The first string is logged
4549// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4550// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4551// another asynchronous call is used to clear the delegate information
4552// before calling a callback. The object then deletes itself.
4553class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4554 public:
4555 typedef base::Callback<void()> Callback;
4556
4557 // Each time delegate information is added to the URLRequest, the resulting
4558 // load state is checked. The expected load state after each request is
4559 // passed in as an argument.
4560 static void Run(URLRequest* url_request,
4561 LoadState expected_first_load_state,
4562 LoadState expected_second_load_state,
4563 LoadState expected_third_load_state,
4564 const Callback& callback) {
4565 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4566 url_request,
4567 expected_first_load_state,
4568 expected_second_load_state,
4569 expected_third_load_state,
4570 callback);
4571 logger->Start();
4572 }
4573
4574 // Checks that the log entries, starting with log_position, contain the
4575 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4576 // recorded. Returns the index of entry after the expected number of
4577 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464578 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514579 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514580 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4581 if (log_position + 3 >= entries.size()) {
4582 ADD_FAILURE() << "Not enough log entries";
4583 return entries.size();
4584 }
4585 std::string delegate_info;
4586 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4587 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4588 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4589 &delegate_info));
4590 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4591
4592 ++log_position;
4593 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4594 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4595
4596 ++log_position;
4597 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4598 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4599 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4600 &delegate_info));
4601 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4602
4603 ++log_position;
4604 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4605 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4606
4607 return log_position + 1;
4608 }
4609
[email protected]1826a402014-01-08 15:40:484610 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4611 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464612 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4613 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484614 log_position =
4615 ExpectLogContainsSomewhereAfter(entries,
4616 log_position,
4617 NetLog::TYPE_URL_REQUEST_DELEGATE,
4618 NetLog::PHASE_BEGIN);
4619 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4620 entries[log_position + 1].type);
4621 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4622 return log_position + 1;
4623 }
4624
[email protected]abe1c4a2013-10-25 19:28:514625 private:
4626 friend class base::RefCounted<AsyncDelegateLogger>;
4627
4628 AsyncDelegateLogger(URLRequest* url_request,
4629 LoadState expected_first_load_state,
4630 LoadState expected_second_load_state,
4631 LoadState expected_third_load_state,
4632 const Callback& callback)
4633 : url_request_(url_request),
4634 expected_first_load_state_(expected_first_load_state),
4635 expected_second_load_state_(expected_second_load_state),
4636 expected_third_load_state_(expected_third_load_state),
4637 callback_(callback) {
4638 }
4639
4640 ~AsyncDelegateLogger() {}
4641
4642 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534643 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514644 LoadStateWithParam load_state = url_request_->GetLoadState();
4645 EXPECT_EQ(expected_first_load_state_, load_state.state);
4646 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454647 base::ThreadTaskRunnerHandle::Get()->PostTask(
4648 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514649 }
4650
4651 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534652 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514653 LoadStateWithParam load_state = url_request_->GetLoadState();
4654 EXPECT_EQ(expected_second_load_state_, load_state.state);
4655 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4656 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4657 } else {
4658 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4659 }
skyostil4891b25b2015-06-11 11:43:454660 base::ThreadTaskRunnerHandle::Get()->PostTask(
4661 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514662 }
4663
4664 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534665 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514666 LoadStateWithParam load_state = url_request_->GetLoadState();
4667 EXPECT_EQ(expected_third_load_state_, load_state.state);
4668 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084669 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514670 callback_.Run();
4671 }
4672
4673 URLRequest* url_request_;
4674 const int expected_first_load_state_;
4675 const int expected_second_load_state_;
4676 const int expected_third_load_state_;
4677 const Callback callback_;
4678
4679 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4680};
4681
4682// NetworkDelegate that logs delegate information before a request is started,
4683// before headers are sent, when headers are read, and when auth information
4684// is requested. Uses AsyncDelegateLogger.
4685class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4686 public:
4687 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204688 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514689
4690 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204691 int OnBeforeURLRequest(URLRequest* request,
4692 const CompletionCallback& callback,
4693 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514694 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4695 return RunCallbackAsynchronously(request, callback);
4696 }
4697
dchengb03027d2014-10-21 12:00:204698 int OnBeforeSendHeaders(URLRequest* request,
4699 const CompletionCallback& callback,
4700 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514701 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4702 return RunCallbackAsynchronously(request, callback);
4703 }
4704
dchengb03027d2014-10-21 12:00:204705 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514706 URLRequest* request,
4707 const CompletionCallback& callback,
4708 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164709 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134710 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164711 TestNetworkDelegate::OnHeadersReceived(request,
4712 callback,
[email protected]abe1c4a2013-10-25 19:28:514713 original_response_headers,
[email protected]5f714132014-03-26 10:41:164714 override_response_headers,
4715 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514716 return RunCallbackAsynchronously(request, callback);
4717 }
4718
dchengb03027d2014-10-21 12:00:204719 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514720 URLRequest* request,
4721 const AuthChallengeInfo& auth_info,
4722 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134723 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514724 AsyncDelegateLogger::Run(
4725 request,
4726 LOAD_STATE_WAITING_FOR_DELEGATE,
4727 LOAD_STATE_WAITING_FOR_DELEGATE,
4728 LOAD_STATE_WAITING_FOR_DELEGATE,
4729 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4730 callback, credentials));
4731 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4732 }
4733
4734 private:
4735 static int RunCallbackAsynchronously(
4736 URLRequest* request,
4737 const CompletionCallback& callback) {
4738 AsyncDelegateLogger::Run(
4739 request,
4740 LOAD_STATE_WAITING_FOR_DELEGATE,
4741 LOAD_STATE_WAITING_FOR_DELEGATE,
4742 LOAD_STATE_WAITING_FOR_DELEGATE,
4743 base::Bind(callback, OK));
4744 return ERR_IO_PENDING;
4745 }
4746
4747 static void SetAuthAndResume(const AuthCallback& callback,
4748 AuthCredentials* credentials) {
4749 *credentials = AuthCredentials(kUser, kSecret);
4750 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4751 }
4752
4753 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4754};
4755
4756// URLRequest::Delegate that logs delegate information when the headers
4757// are received, when each read completes, and during redirects. Uses
4758// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4759//
4760// Inherits from TestDelegate to reuse the TestDelegate code to handle
4761// advancing to the next step in most cases, as well as cancellation.
4762class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4763 public:
4764 enum CancelStage {
4765 NO_CANCEL = 0,
4766 CANCEL_ON_RECEIVED_REDIRECT,
4767 CANCEL_ON_RESPONSE_STARTED,
4768 CANCEL_ON_READ_COMPLETED
4769 };
4770
4771 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4772 : cancel_stage_(cancel_stage) {
4773 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4774 set_cancel_in_received_redirect(true);
4775 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4776 set_cancel_in_response_started(true);
4777 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4778 set_cancel_in_received_data(true);
4779 }
dchengb03027d2014-10-21 12:00:204780 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514781
4782 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204783 void OnReceivedRedirect(URLRequest* request,
4784 const RedirectInfo& redirect_info,
4785 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514786 *defer_redirect = true;
4787 AsyncDelegateLogger::Run(
4788 request,
4789 LOAD_STATE_WAITING_FOR_DELEGATE,
4790 LOAD_STATE_WAITING_FOR_DELEGATE,
4791 LOAD_STATE_WAITING_FOR_DELEGATE,
4792 base::Bind(
4793 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594794 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514795 }
4796
dchengb03027d2014-10-21 12:00:204797 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514798 AsyncDelegateLogger::Run(
4799 request,
4800 LOAD_STATE_WAITING_FOR_DELEGATE,
4801 LOAD_STATE_WAITING_FOR_DELEGATE,
4802 LOAD_STATE_WAITING_FOR_DELEGATE,
4803 base::Bind(
4804 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4805 base::Unretained(this), request));
4806 }
4807
dchengb03027d2014-10-21 12:00:204808 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514809 AsyncDelegateLogger::Run(
4810 request,
4811 LOAD_STATE_IDLE,
4812 LOAD_STATE_IDLE,
4813 LOAD_STATE_IDLE,
4814 base::Bind(
4815 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4816 base::Unretained(this), request, bytes_read));
4817 }
4818
4819 private:
4820 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594821 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514822 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594823 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514824 // FollowDeferredRedirect should not be called after cancellation.
4825 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4826 return;
4827 if (!defer_redirect)
4828 request->FollowDeferredRedirect();
4829 }
4830
4831 void OnResponseStartedLoggingComplete(URLRequest* request) {
4832 // The parent class continues the request.
4833 TestDelegate::OnResponseStarted(request);
4834 }
4835
4836 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4837 // The parent class continues the request.
4838 TestDelegate::OnReadCompleted(request, bytes_read);
4839 }
4840
4841 const CancelStage cancel_stage_;
4842
4843 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4844};
4845
4846// Tests handling of delegate info before a request starts.
4847TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:554848 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:514849
4850 TestDelegate request_delegate;
4851 TestURLRequestContext context(true);
4852 context.set_network_delegate(NULL);
4853 context.set_net_log(&net_log_);
4854 context.Init();
4855
4856 {
davidben151423e2015-03-23 18:48:364857 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:554858 context.CreateRequest(http_test_server()->GetURL("/defaultresponse"),
davidben151423e2015-03-23 18:48:364859 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194860 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514861 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084862 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514863
4864 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194865 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514866 LOAD_STATE_WAITING_FOR_DELEGATE,
4867 LOAD_STATE_WAITING_FOR_DELEGATE,
4868 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194869 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514870
4871 base::RunLoop().Run();
4872
[email protected]f7022f32014-08-21 16:32:194873 EXPECT_EQ(200, r->GetResponseCode());
4874 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514875 }
4876
mmenke43758e62015-05-04 21:09:464877 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514878 net_log_.GetEntries(&entries);
4879 size_t log_position = ExpectLogContainsSomewhereAfter(
4880 entries,
4881 0,
4882 NetLog::TYPE_DELEGATE_INFO,
4883 NetLog::PHASE_BEGIN);
4884
4885 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4886
4887 // Nothing else should add any delegate info to the request.
4888 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4889 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4890}
4891
4892// Tests handling of delegate info from a network delegate.
4893TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:554894 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:514895
4896 TestDelegate request_delegate;
4897 AsyncLoggingNetworkDelegate network_delegate;
4898 TestURLRequestContext context(true);
4899 context.set_network_delegate(&network_delegate);
4900 context.set_net_log(&net_log_);
4901 context.Init();
4902
4903 {
davidben151423e2015-03-23 18:48:364904 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:554905 context.CreateRequest(http_test_server()->GetURL("/simple.html"),
davidben151423e2015-03-23 18:48:364906 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194907 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514908 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084909 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514910
[email protected]f7022f32014-08-21 16:32:194911 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514912 base::RunLoop().Run();
4913
[email protected]f7022f32014-08-21 16:32:194914 EXPECT_EQ(200, r->GetResponseCode());
4915 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514916 EXPECT_EQ(1, network_delegate.created_requests());
4917 EXPECT_EQ(0, network_delegate.destroyed_requests());
4918 }
4919 EXPECT_EQ(1, network_delegate.destroyed_requests());
4920
4921 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464922 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514923 net_log_.GetEntries(&entries);
4924 for (size_t i = 0; i < 3; ++i) {
4925 log_position = ExpectLogContainsSomewhereAfter(
4926 entries,
4927 log_position + 1,
4928 NetLog::TYPE_URL_REQUEST_DELEGATE,
4929 NetLog::PHASE_BEGIN);
4930
4931 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4932 log_position + 1);
4933
4934 ASSERT_LT(log_position, entries.size());
4935 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4936 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484937
4938 if (i == 1) {
4939 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4940 entries, log_position + 1);
4941 }
[email protected]abe1c4a2013-10-25 19:28:514942 }
4943
4944 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4945 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4946}
4947
4948// Tests handling of delegate info from a network delegate in the case of an
4949// HTTP redirect.
4950TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:554951 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:514952
4953 TestDelegate request_delegate;
4954 AsyncLoggingNetworkDelegate network_delegate;
4955 TestURLRequestContext context(true);
4956 context.set_network_delegate(&network_delegate);
4957 context.set_net_log(&net_log_);
4958 context.Init();
4959
4960 {
[email protected]f7022f32014-08-21 16:32:194961 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554962 http_test_server()->GetURL("/server-redirect?simple.html"),
4963 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194964 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514965 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084966 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514967
[email protected]f7022f32014-08-21 16:32:194968 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514969 base::RunLoop().Run();
4970
[email protected]f7022f32014-08-21 16:32:194971 EXPECT_EQ(200, r->GetResponseCode());
4972 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514973 EXPECT_EQ(2, network_delegate.created_requests());
4974 EXPECT_EQ(0, network_delegate.destroyed_requests());
4975 }
4976 EXPECT_EQ(1, network_delegate.destroyed_requests());
4977
4978 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464979 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514980 net_log_.GetEntries(&entries);
4981 // The NetworkDelegate logged information in OnBeforeURLRequest,
4982 // OnBeforeSendHeaders, and OnHeadersReceived.
4983 for (size_t i = 0; i < 3; ++i) {
4984 log_position = ExpectLogContainsSomewhereAfter(
4985 entries,
4986 log_position + 1,
4987 NetLog::TYPE_URL_REQUEST_DELEGATE,
4988 NetLog::PHASE_BEGIN);
4989
4990 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4991 log_position + 1);
4992
4993 ASSERT_LT(log_position, entries.size());
4994 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4995 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484996
4997 if (i == 1) {
4998 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4999 entries, log_position + 1);
5000 }
[email protected]abe1c4a2013-10-25 19:28:515001 }
5002
5003 // The URLRequest::Delegate then gets informed about the redirect.
5004 log_position = ExpectLogContainsSomewhereAfter(
5005 entries,
5006 log_position + 1,
5007 NetLog::TYPE_URL_REQUEST_DELEGATE,
5008 NetLog::PHASE_BEGIN);
5009
5010 // The NetworkDelegate logged information in the same three events as before.
5011 for (size_t i = 0; i < 3; ++i) {
5012 log_position = ExpectLogContainsSomewhereAfter(
5013 entries,
5014 log_position + 1,
5015 NetLog::TYPE_URL_REQUEST_DELEGATE,
5016 NetLog::PHASE_BEGIN);
5017
5018 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5019 log_position + 1);
5020
5021 ASSERT_LT(log_position, entries.size());
5022 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5023 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5024 }
5025
5026 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5027 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5028}
5029
5030// Tests handling of delegate info from a network delegate in the case of HTTP
5031// AUTH.
5032TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555033 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515034
5035 TestDelegate request_delegate;
5036 AsyncLoggingNetworkDelegate network_delegate;
5037 TestURLRequestContext context(true);
5038 context.set_network_delegate(&network_delegate);
5039 context.set_net_log(&net_log_);
5040 context.Init();
5041
5042 {
davidben151423e2015-03-23 18:48:365043 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555044 context.CreateRequest(http_test_server()->GetURL("/auth-basic"),
davidben151423e2015-03-23 18:48:365045 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195046 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515047 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085048 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515049
[email protected]f7022f32014-08-21 16:32:195050 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515051 base::RunLoop().Run();
5052
[email protected]f7022f32014-08-21 16:32:195053 EXPECT_EQ(200, r->GetResponseCode());
5054 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515055 EXPECT_EQ(1, network_delegate.created_requests());
5056 EXPECT_EQ(0, network_delegate.destroyed_requests());
5057 }
5058 EXPECT_EQ(1, network_delegate.destroyed_requests());
5059
5060 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465061 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515062 net_log_.GetEntries(&entries);
5063 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
5064 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
5065 // OnBeforeURLRequest and OnBeforeSendHeaders.
5066 for (size_t i = 0; i < 6; ++i) {
5067 log_position = ExpectLogContainsSomewhereAfter(
5068 entries,
5069 log_position + 1,
5070 NetLog::TYPE_URL_REQUEST_DELEGATE,
5071 NetLog::PHASE_BEGIN);
5072
5073 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5074 log_position + 1);
5075
5076 ASSERT_LT(log_position, entries.size());
5077 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5078 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485079
5080 if (i == 1) {
5081 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5082 entries, log_position + 1);
5083 }
[email protected]abe1c4a2013-10-25 19:28:515084 }
5085
5086 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5087 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5088}
5089
tommycli59a63432015-11-06 00:10:555090// TODO(svaldez): Update tests to use EmbeddedTestServer.
5091#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515092// Tests handling of delegate info from a URLRequest::Delegate.
5093TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555094 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
5095 SpawnedTestServer::kLocalhost,
5096 base::FilePath(kTestFilePath));
5097
5098 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515099
5100 AsyncLoggingUrlRequestDelegate request_delegate(
5101 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5102 TestURLRequestContext context(true);
5103 context.set_network_delegate(NULL);
5104 context.set_net_log(&net_log_);
5105 context.Init();
5106
5107 {
5108 // A chunked response with delays between chunks is used to make sure that
5109 // attempts by the URLRequest delegate to log information while reading the
5110 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485111 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515112 // that it occurs.
[email protected]f7022f32014-08-21 16:32:195113 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555114 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365115 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195116 LoadStateWithParam load_state = r->GetLoadState();
5117 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515118 base::RunLoop().Run();
5119
[email protected]f7022f32014-08-21 16:32:195120 EXPECT_EQ(200, r->GetResponseCode());
5121 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515122 }
5123
mmenke43758e62015-05-04 21:09:465124 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515125 net_log_.GetEntries(&entries);
5126
[email protected]1826a402014-01-08 15:40:485127 size_t log_position = 0;
5128
5129 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5130 entries, log_position);
5131
[email protected]abe1c4a2013-10-25 19:28:515132 // The delegate info should only have been logged on header complete. Other
5133 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:485134 log_position =
5135 ExpectLogContainsSomewhereAfter(entries,
5136 log_position + 1,
5137 NetLog::TYPE_URL_REQUEST_DELEGATE,
5138 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515139
5140 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5141 log_position + 1);
5142
5143 ASSERT_LT(log_position, entries.size());
5144 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5145 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5146
5147 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5148 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5149 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5150 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5151}
tommycli59a63432015-11-06 00:10:555152#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515153
5154// Tests handling of delegate info from a URLRequest::Delegate in the case of
5155// an HTTP redirect.
5156TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555157 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515158
5159 AsyncLoggingUrlRequestDelegate request_delegate(
5160 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5161 TestURLRequestContext context(true);
5162 context.set_network_delegate(NULL);
5163 context.set_net_log(&net_log_);
5164 context.Init();
5165
5166 {
[email protected]f7022f32014-08-21 16:32:195167 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555168 http_test_server()->GetURL("/server-redirect?simple.html"),
5169 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195170 LoadStateWithParam load_state = r->GetLoadState();
5171 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515172 base::RunLoop().Run();
5173
[email protected]f7022f32014-08-21 16:32:195174 EXPECT_EQ(200, r->GetResponseCode());
5175 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515176 }
5177
mmenke43758e62015-05-04 21:09:465178 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515179 net_log_.GetEntries(&entries);
5180
5181 // Delegate info should only have been logged in OnReceivedRedirect and
5182 // OnResponseStarted.
5183 size_t log_position = 0;
5184 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485185 if (i == 0) {
5186 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5187 entries, log_position) + 1;
5188 }
5189
[email protected]abe1c4a2013-10-25 19:28:515190 log_position = ExpectLogContainsSomewhereAfter(
5191 entries,
5192 log_position,
5193 NetLog::TYPE_URL_REQUEST_DELEGATE,
5194 NetLog::PHASE_BEGIN);
5195
5196 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5197 log_position + 1);
5198
5199 ASSERT_LT(log_position, entries.size());
5200 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5201 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5202 }
5203
5204 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5205 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5206 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5207 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5208}
5209
5210// Tests handling of delegate info from a URLRequest::Delegate in the case of
5211// an HTTP redirect, with cancellation at various points.
5212TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555213 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515214
5215 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5216 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5217 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5218 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5219 };
5220
5221 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5222 ++test_case) {
5223 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5224 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:515225 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:515226 context.set_network_delegate(NULL);
5227 context.set_net_log(&net_log);
5228 context.Init();
5229
5230 {
[email protected]f7022f32014-08-21 16:32:195231 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555232 http_test_server()->GetURL("/server-redirect?simple.html"),
5233 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195234 LoadStateWithParam load_state = r->GetLoadState();
5235 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515236 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195237 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515238 }
5239
mmenke43758e62015-05-04 21:09:465240 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515241 net_log.GetEntries(&entries);
5242
5243 // Delegate info is always logged in both OnReceivedRedirect and
5244 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5245 // OnResponseStarted delegate call is after cancellation, but logging is
5246 // still currently supported in that call.
5247 size_t log_position = 0;
5248 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485249 if (i == 0) {
5250 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5251 entries, log_position) + 1;
5252 }
5253
[email protected]abe1c4a2013-10-25 19:28:515254 log_position = ExpectLogContainsSomewhereAfter(
5255 entries,
5256 log_position,
5257 NetLog::TYPE_URL_REQUEST_DELEGATE,
5258 NetLog::PHASE_BEGIN);
5259
5260 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5261 log_position + 1);
5262
5263 ASSERT_LT(log_position, entries.size());
5264 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5265 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5266 }
5267
5268 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5269 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5270 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5271 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5272 }
5273}
5274
[email protected]847c0fa92012-11-06 16:37:425275namespace {
5276
5277const char kExtraHeader[] = "Allow-Snafu";
5278const char kExtraValue[] = "fubar";
5279
5280class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205281 void OnReceivedRedirect(URLRequest* request,
5282 const RedirectInfo& redirect_info,
5283 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595284 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425285 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5286 }
5287};
5288
5289} // namespace
5290
5291TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555292 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425293
tommycli59a63432015-11-06 00:10:555294 GURL destination_url =
5295 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5296 GURL original_url =
5297 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425298 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:365299 scoped_ptr<URLRequest> req(
5300 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195301 req->Start();
[email protected]255620da2013-08-19 13:14:295302 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425303
5304 std::string value;
[email protected]f7022f32014-08-21 16:32:195305 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425306 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5307 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195308 EXPECT_FALSE(req->is_pending());
5309 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425310 EXPECT_EQ(kExtraValue, d.data_received());
5311}
5312
[email protected]251a1b92012-11-13 11:01:095313namespace {
5314
5315const char kExtraHeaderToRemove[] = "To-Be-Removed";
5316
5317class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205318 void OnReceivedRedirect(URLRequest* request,
5319 const RedirectInfo& redirect_info,
5320 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595321 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095322 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5323 }
5324};
5325
5326} // namespace
5327
5328TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555329 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095330
tommycli59a63432015-11-06 00:10:555331 GURL destination_url = http_test_server()->GetURL(
5332 "/echoheader?" + std::string(kExtraHeaderToRemove));
5333 GURL original_url =
5334 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095335 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:365336 scoped_ptr<URLRequest> req(
5337 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195338 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5339 req->Start();
[email protected]255620da2013-08-19 13:14:295340 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095341
5342 std::string value;
[email protected]f7022f32014-08-21 16:32:195343 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095344 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195345 EXPECT_FALSE(req->is_pending());
5346 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095347 EXPECT_EQ("None", d.data_received());
5348}
5349
[email protected]316c1e5e2012-09-12 15:17:445350TEST_F(URLRequestTestHTTP, CancelTest) {
5351 TestDelegate d;
5352 {
[email protected]f7022f32014-08-21 16:32:195353 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365354 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445355
[email protected]f7022f32014-08-21 16:32:195356 r->Start();
5357 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445358
[email protected]f7022f32014-08-21 16:32:195359 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445360
[email protected]255620da2013-08-19 13:14:295361 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445362
5363 // We expect to receive OnResponseStarted even though the request has been
5364 // cancelled.
5365 EXPECT_EQ(1, d.response_started_count());
5366 EXPECT_EQ(0, d.bytes_received());
5367 EXPECT_FALSE(d.received_data_before_response());
5368 }
5369}
5370
5371TEST_F(URLRequestTestHTTP, CancelTest2) {
tommycli59a63432015-11-06 00:10:555372 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445373
5374 TestDelegate d;
5375 {
[email protected]f7022f32014-08-21 16:32:195376 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555377 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445378
5379 d.set_cancel_in_response_started(true);
5380
[email protected]f7022f32014-08-21 16:32:195381 r->Start();
5382 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445383
[email protected]255620da2013-08-19 13:14:295384 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445385
5386 EXPECT_EQ(1, d.response_started_count());
5387 EXPECT_EQ(0, d.bytes_received());
5388 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195389 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445390 }
5391}
5392
5393TEST_F(URLRequestTestHTTP, CancelTest3) {
tommycli59a63432015-11-06 00:10:555394 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445395
5396 TestDelegate d;
5397 {
[email protected]f7022f32014-08-21 16:32:195398 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555399 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445400
5401 d.set_cancel_in_received_data(true);
5402
[email protected]f7022f32014-08-21 16:32:195403 r->Start();
5404 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445405
[email protected]255620da2013-08-19 13:14:295406 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445407
5408 EXPECT_EQ(1, d.response_started_count());
5409 // There is no guarantee about how much data was received
5410 // before the cancel was issued. It could have been 0 bytes,
5411 // or it could have been all the bytes.
5412 // EXPECT_EQ(0, d.bytes_received());
5413 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195414 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445415 }
5416}
5417
5418TEST_F(URLRequestTestHTTP, CancelTest4) {
tommycli59a63432015-11-06 00:10:555419 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445420
5421 TestDelegate d;
5422 {
[email protected]f7022f32014-08-21 16:32:195423 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555424 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445425
[email protected]f7022f32014-08-21 16:32:195426 r->Start();
5427 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445428
5429 // The request will be implicitly canceled when it is destroyed. The
5430 // test delegate must not post a quit message when this happens because
5431 // this test doesn't actually have a message loop. The quit message would
5432 // get put on this thread's message queue and the next test would exit
5433 // early, causing problems.
5434 d.set_quit_on_complete(false);
5435 }
5436 // expect things to just cleanup properly.
5437
kimwjdalsl2bb4ff02015-12-16 22:06:025438 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:445439 // message loop
5440 EXPECT_FALSE(d.received_data_before_response());
5441 EXPECT_EQ(0, d.bytes_received());
5442}
5443
5444TEST_F(URLRequestTestHTTP, CancelTest5) {
tommycli59a63432015-11-06 00:10:555445 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445446
5447 // populate cache
5448 {
5449 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195450 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555451 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195452 r->Start();
[email protected]255620da2013-08-19 13:14:295453 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195454 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445455 }
5456
5457 // cancel read from cache (see bug 990242)
5458 {
5459 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195460 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555461 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195462 r->Start();
5463 r->Cancel();
[email protected]255620da2013-08-19 13:14:295464 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445465
[email protected]f7022f32014-08-21 16:32:195466 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445467 EXPECT_EQ(1, d.response_started_count());
5468 EXPECT_EQ(0, d.bytes_received());
5469 EXPECT_FALSE(d.received_data_before_response());
5470 }
5471}
5472
5473TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:555474 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445475 HTTPUploadDataOperationTest("POST");
5476}
5477
5478TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:555479 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445480 HTTPUploadDataOperationTest("PUT");
5481}
5482
5483TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:555484 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445485
5486 TestDelegate d;
5487 {
[email protected]f7022f32014-08-21 16:32:195488 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555489 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195490 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445491
[email protected]f7022f32014-08-21 16:32:195492 r->Start();
5493 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445494
[email protected]255620da2013-08-19 13:14:295495 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445496
[email protected]329b68b2012-11-14 17:54:275497 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195498 << "request failed: " << r->status().status()
5499 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445500
5501 EXPECT_FALSE(d.received_data_before_response());
5502 EXPECT_TRUE(d.data_received().empty());
5503 }
5504}
5505
5506TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:555507 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445508
5509 TestDelegate d;
5510 {
[email protected]f7022f32014-08-21 16:32:195511 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555512 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195513 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445514
[email protected]6cdfd7f2013-02-08 20:40:155515 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445516 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025517 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445518
olli.raula6df48b2a2015-11-26 07:40:225519 std::vector<scoped_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445520
[email protected]6cdfd7f2013-02-08 20:40:155521 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445522 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475523 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445524 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
avibf0746c2015-12-09 19:53:145525 element_readers.push_back(make_scoped_ptr(new UploadFileElementReader(
5526 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
5527 std::numeric_limits<uint64_t>::max(), base::Time())));
mmenkecbc2b712014-10-09 20:29:075528 r->set_upload(make_scoped_ptr<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225529 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:445530
[email protected]f7022f32014-08-21 16:32:195531 r->Start();
5532 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445533
[email protected]255620da2013-08-19 13:14:295534 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445535
avibf0746c2015-12-09 19:53:145536 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:295537 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5538 ASSERT_LE(size64, std::numeric_limits<int>::max());
5539 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175540 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445541
[email protected]7600d0b2013-12-08 21:43:305542 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445543
[email protected]329b68b2012-11-14 17:54:275544 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195545 << "request failed: " << r->status().status()
5546 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445547
5548 EXPECT_FALSE(d.received_data_before_response());
5549
[email protected]329b68b2012-11-14 17:54:275550 EXPECT_EQ(size, d.bytes_received());
5551 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445552 }
5553}
5554
[email protected]999dd8c2013-11-12 06:45:545555TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:555556 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:545557
5558 TestDelegate d;
5559 {
[email protected]f7022f32014-08-21 16:32:195560 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555561 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195562 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545563
olli.raula6df48b2a2015-11-26 07:40:225564 std::vector<scoped_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:545565
olli.raula6df48b2a2015-11-26 07:40:225566 element_readers.push_back(make_scoped_ptr(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455567 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545568 base::FilePath(FILE_PATH_LITERAL(
5569 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
avibf0746c2015-12-09 19:53:145570 0, std::numeric_limits<uint64_t>::max(), base::Time())));
mmenkecbc2b712014-10-09 20:29:075571 r->set_upload(make_scoped_ptr<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225572 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:545573
[email protected]f7022f32014-08-21 16:32:195574 r->Start();
5575 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545576
5577 base::RunLoop().Run();
5578
[email protected]999dd8c2013-11-12 06:45:545579 EXPECT_TRUE(d.request_failed());
5580 EXPECT_FALSE(d.received_data_before_response());
5581 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195582 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5583 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545584 }
5585}
5586
[email protected]316c1e5e2012-09-12 15:17:445587TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:555588 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445589
5590 TestDelegate d;
5591 {
[email protected]f7022f32014-08-21 16:32:195592 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555593 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195594 r->EnableChunkedUpload();
5595 r->set_method("POST");
5596 AddChunksToUpload(r.get());
5597 r->Start();
5598 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445599
[email protected]255620da2013-08-19 13:14:295600 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445601
[email protected]f7022f32014-08-21 16:32:195602 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445603 }
5604}
5605
[email protected]329b68b2012-11-14 17:54:275606TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:555607 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:275608
5609 TestDelegate d;
5610 {
[email protected]f7022f32014-08-21 16:32:195611 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555612 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195613 r->EnableChunkedUpload();
5614 r->set_method("POST");
5615 r->Start();
5616 EXPECT_TRUE(r->is_pending());
5617 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295618 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275619
[email protected]f7022f32014-08-21 16:32:195620 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275621 }
5622}
5623
[email protected]316c1e5e2012-09-12 15:17:445624TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:555625 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445626
5627 TestDelegate d;
5628 {
[email protected]f7022f32014-08-21 16:32:195629 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555630 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195631 r->EnableChunkedUpload();
5632 r->set_method("POST");
5633 r->Start();
5634 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445635
[email protected]255620da2013-08-19 13:14:295636 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195637 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295638 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445639
[email protected]f7022f32014-08-21 16:32:195640 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445641 }
5642}
5643
5644TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:555645 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445646
5647 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195648 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555649 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195650 req->Start();
[email protected]255620da2013-08-19 13:14:295651 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445652
[email protected]f7022f32014-08-21 16:32:195653 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445654
5655 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195656 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445657
5658 std::string header;
5659 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5660 EXPECT_EQ("private", header);
5661
5662 header.clear();
5663 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5664 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5665
5666 // The response has two "X-Multiple-Entries" headers.
5667 // This verfies our output has them concatenated together.
5668 header.clear();
5669 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5670 EXPECT_EQ("a, b", header);
5671}
5672
tommycli59a63432015-11-06 00:10:555673// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
5674// security state. (see http://crbug.com/550977).
5675#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:465676TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:555677 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5678 https_test_server.SetSSLConfig(
5679 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5680 https_test_server.ServeFilesFromSourceDirectory(
5681 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465682 ASSERT_TRUE(https_test_server.Start());
5683
tommycli59a63432015-11-06 00:10:555684 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:465685 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195686 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555687 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195688 request->Start();
[email protected]255620da2013-08-19 13:14:295689 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465690
5691 TransportSecurityState* security_state =
5692 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405693 TransportSecurityState::STSState sts_state;
5694 TransportSecurityState::PKPState pkp_state;
5695 EXPECT_TRUE(
5696 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5697 EXPECT_FALSE(
5698 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5699 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5700 sts_state.upgrade_mode);
5701 EXPECT_TRUE(sts_state.include_subdomains);
5702 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:035703#if defined(OS_ANDROID)
5704 // Android's CertVerifyProc does not (yet) handle pins.
5705#else
martijnc0d6b622015-06-30 19:14:405706 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035707#endif
[email protected]37fd55fb2013-06-29 13:13:275708}
5709
estarka5da76702015-04-09 04:00:165710TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555711 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5712 https_test_server.ServeFilesFromSourceDirectory(
5713 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165714 ASSERT_TRUE(https_test_server.Start());
5715 // Make sure this test fails if the test server is changed to not
5716 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555717 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5718 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165719
5720 TestDelegate d;
5721 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555722 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:165723 request->Start();
5724 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:165725 TransportSecurityState* security_state =
5726 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405727 TransportSecurityState::STSState sts_state;
5728 EXPECT_FALSE(
5729 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165730}
5731
mathpc992e602015-10-21 20:34:035732// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5733// reject HPKP headers, and a test setting only HPKP headers will fail (no
5734// PKPState present because header rejected).
5735#if defined(OS_ANDROID)
5736#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5737#define MAYBE_ProcessPKPAndSendReport DISABLED_ProcessPKPAndSendReport
5738#define MAYBE_ProcessPKPReportOnly DISABLED_ProcessPKPReportOnly
5739#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5740 DISABLED_ProcessPKPReportOnlyWithNoViolation
5741#else
5742#define MAYBE_ProcessPKP ProcessPKP
5743#define MAYBE_ProcessPKPAndSendReport ProcessPKPAndSendReport
5744#define MAYBE_ProcessPKPReportOnly ProcessPKPReportOnly
5745#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5746 ProcessPKPReportOnlyWithNoViolation
5747#endif
5748
estark06e0dac2015-08-07 21:56:015749namespace {
5750const char kHPKPReportUri[] = "https://hpkp-report.test";
5751} // namespace
5752
[email protected]37fd55fb2013-06-29 13:13:275753// Tests that enabling HPKP on a domain does not affect the HSTS
5754// validity/expiration.
mathpc992e602015-10-21 20:34:035755TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estark06e0dac2015-08-07 21:56:015756 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555757 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5758 https_test_server.SetSSLConfig(
5759 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5760 https_test_server.ServeFilesFromSourceDirectory(
5761 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275762 ASSERT_TRUE(https_test_server.Start());
5763
tommycli59a63432015-11-06 00:10:555764 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165765
[email protected]37fd55fb2013-06-29 13:13:275766 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195767 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555768 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195769 request->Start();
[email protected]255620da2013-08-19 13:14:295770 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275771 TransportSecurityState* security_state =
5772 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405773 TransportSecurityState::STSState sts_state;
5774 TransportSecurityState::PKPState pkp_state;
5775 EXPECT_FALSE(
5776 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5777 EXPECT_TRUE(
5778 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5779 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
5780 sts_state.upgrade_mode);
5781 EXPECT_FALSE(sts_state.include_subdomains);
5782 EXPECT_FALSE(pkp_state.include_subdomains);
5783 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:015784 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:405785 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:465786}
5787
estark06e0dac2015-08-07 21:56:015788// Tests that reports get sent on HPKP violations when a report-uri is set.
mathpc992e602015-10-21 20:34:035789TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:015790 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555791 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5792 https_test_server.SetSSLConfig(
5793 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5794 https_test_server.ServeFilesFromSourceDirectory(
5795 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015796 ASSERT_TRUE(https_test_server.Start());
5797
tommycli59a63432015-11-06 00:10:555798 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015799
5800 // Set up a pin for |test_server_hostname|.
5801 TransportSecurityState security_state;
5802 const base::Time current_time(base::Time::Now());
5803 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
5804 HashValueVector hashes;
5805 HashValue hash1;
5806 HashValue hash2;
5807 // The values here don't matter, as long as they are different from
5808 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:445809 ASSERT_TRUE(
5810 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
5811 ASSERT_TRUE(
5812 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:015813 hashes.push_back(hash1);
5814 hashes.push_back(hash2);
5815 security_state.AddHPKP(test_server_hostname, expiry,
5816 false, /* include subdomains */
5817 hashes, report_uri);
5818
5819 MockCertificateReportSender mock_report_sender;
5820 security_state.SetReportSender(&mock_report_sender);
5821
5822 // Set up a MockCertVerifier to trigger a violation of the previously
5823 // set pin.
5824 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5825 ASSERT_TRUE(cert);
5826
5827 MockCertVerifier cert_verifier;
5828 CertVerifyResult verify_result;
5829 verify_result.verified_cert = cert;
5830 verify_result.is_issued_by_known_root = true;
5831 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:445832 ASSERT_TRUE(
5833 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:015834 verify_result.public_key_hashes.push_back(hash3);
5835 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5836
5837 TestNetworkDelegate network_delegate;
5838 TestURLRequestContext context(true);
5839 context.set_transport_security_state(&security_state);
5840 context.set_network_delegate(&network_delegate);
5841 context.set_cert_verifier(&cert_verifier);
5842 context.Init();
5843
5844 // Now send a request to trigger the violation.
5845 TestDelegate d;
5846 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555847 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
estark06e0dac2015-08-07 21:56:015848 violating_request->Start();
5849 base::RunLoop().Run();
5850
5851 // Check that a report was sent.
5852 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5853 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5854 scoped_ptr<base::Value> value(
5855 base::JSONReader::Read(mock_report_sender.latest_report()));
5856 ASSERT_TRUE(value);
5857 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
5858 base::DictionaryValue* report_dict;
5859 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
5860 std::string report_hostname;
5861 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
5862 EXPECT_EQ(test_server_hostname, report_hostname);
5863}
5864
5865// Tests that reports get sent on requests with
5866// Public-Key-Pins-Report-Only headers.
mathpc992e602015-10-21 20:34:035867TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:015868 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555869 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5870 https_test_server.SetSSLConfig(
5871 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5872 https_test_server.ServeFilesFromSourceDirectory(
5873 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015874 ASSERT_TRUE(https_test_server.Start());
5875
tommycli59a63432015-11-06 00:10:555876 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015877
5878 TransportSecurityState security_state;
5879 MockCertificateReportSender mock_report_sender;
5880 security_state.SetReportSender(&mock_report_sender);
5881
5882 // Set up a MockCertVerifier to violate the pin in the Report-Only
5883 // header.
5884 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5885 ASSERT_TRUE(cert);
5886
5887 MockCertVerifier cert_verifier;
5888 CertVerifyResult verify_result;
5889 verify_result.verified_cert = cert;
5890 verify_result.is_issued_by_known_root = true;
5891 HashValue hash;
5892 // This value doesn't matter, as long as it is different from the pins
5893 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:445894 ASSERT_TRUE(
5895 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:015896 verify_result.public_key_hashes.push_back(hash);
5897 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5898
5899 TestNetworkDelegate network_delegate;
5900 TestURLRequestContext context(true);
5901 context.set_transport_security_state(&security_state);
5902 context.set_network_delegate(&network_delegate);
5903 context.set_cert_verifier(&cert_verifier);
5904 context.Init();
5905
5906 // Now send a request to trigger the violation.
5907 TestDelegate d;
5908 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555909 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:015910 DEFAULT_PRIORITY, &d));
5911 violating_request->Start();
5912 base::RunLoop().Run();
5913
5914 // Check that a report was sent.
5915 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5916 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5917 scoped_ptr<base::Value> value(
5918 base::JSONReader::Read(mock_report_sender.latest_report()));
5919 ASSERT_TRUE(value);
5920 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
5921 base::DictionaryValue* report_dict;
5922 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
5923 std::string report_hostname;
5924 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
5925 EXPECT_EQ(test_server_hostname, report_hostname);
5926}
5927
5928// Tests that reports do not get sent on requests with
5929// Public-Key-Pins-Report-Only headers that don't have pin violations.
mathpc992e602015-10-21 20:34:035930TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:015931 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555932 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5933 https_test_server.SetSSLConfig(
5934 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5935 https_test_server.ServeFilesFromSourceDirectory(
5936 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015937 ASSERT_TRUE(https_test_server.Start());
5938
tommycli59a63432015-11-06 00:10:555939 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015940
5941 TransportSecurityState security_state;
5942 MockCertificateReportSender mock_report_sender;
5943 security_state.SetReportSender(&mock_report_sender);
5944
5945 TestNetworkDelegate network_delegate;
5946 MockCertVerifier mock_cert_verifier;
5947 TestURLRequestContext context(true);
5948 context.set_transport_security_state(&security_state);
5949 context.set_network_delegate(&network_delegate);
5950 context.set_cert_verifier(&mock_cert_verifier);
5951 mock_cert_verifier.set_default_result(OK);
5952 context.Init();
5953
5954 // Now send a request that does not trigger the violation.
5955 TestDelegate d;
5956 scoped_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555957 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:015958 DEFAULT_PRIORITY, &d));
5959 request->Start();
5960 base::RunLoop().Run();
5961
5962 // Check that a report was not sent.
5963 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
5964 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
5965}
5966
estarka5da76702015-04-09 04:00:165967TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555968 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5969 https_test_server.ServeFilesFromSourceDirectory(
5970 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165971 ASSERT_TRUE(https_test_server.Start());
5972 // Make sure this test fails if the test server is changed to not
5973 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555974 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5975 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165976
5977 TestDelegate d;
5978 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555979 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:165980 request->Start();
5981 base::RunLoop().Run();
5982
5983 TransportSecurityState* security_state =
5984 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405985 TransportSecurityState::PKPState pkp_state;
5986 EXPECT_FALSE(
5987 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:165988}
5989
[email protected]242d8562012-10-30 21:20:465990TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:555991 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5992 https_test_server.SetSSLConfig(
5993 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5994 https_test_server.ServeFilesFromSourceDirectory(
5995 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465996 ASSERT_TRUE(https_test_server.Start());
5997
tommycli59a63432015-11-06 00:10:555998 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165999
[email protected]242d8562012-10-30 21:20:466000 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196001 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556002 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
6003 &d));
[email protected]f7022f32014-08-21 16:32:196004 request->Start();
[email protected]255620da2013-08-19 13:14:296005 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466006
6007 // We should have set parameters from the first header, not the second.
6008 TransportSecurityState* security_state =
6009 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406010 TransportSecurityState::STSState sts_state;
6011 EXPECT_TRUE(
6012 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6013 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6014 sts_state.upgrade_mode);
6015 EXPECT_FALSE(sts_state.include_subdomains);
6016 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466017}
6018
[email protected]9f972ec2013-04-10 20:24:366019TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556020 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6021 https_test_server.SetSSLConfig(
6022 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6023 https_test_server.ServeFilesFromSourceDirectory(
6024 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366025 ASSERT_TRUE(https_test_server.Start());
6026
tommycli59a63432015-11-06 00:10:556027 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166028
[email protected]9f972ec2013-04-10 20:24:366029 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196030 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556031 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
6032 &d));
[email protected]f7022f32014-08-21 16:32:196033 request->Start();
[email protected]255620da2013-08-19 13:14:296034 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366035
6036 // We should have set parameters from the first header, not the second.
6037 TransportSecurityState* security_state =
6038 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406039 TransportSecurityState::STSState sts_state;
6040 TransportSecurityState::PKPState pkp_state;
6041 EXPECT_TRUE(
6042 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6043 EXPECT_TRUE(
6044 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6045 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6046 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036047#if defined(OS_ANDROID)
6048 // Android's CertVerifyProc does not (yet) handle pins.
6049#else
martijnc0d6b622015-06-30 19:14:406050 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036051#endif
martijnc0d6b622015-06-30 19:14:406052 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366053
[email protected]a165f092013-06-12 16:10:056054 // Even though there is an HSTS header asserting includeSubdomains, it is
6055 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406056 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056057 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406058 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366059}
6060
[email protected]37fd55fb2013-06-29 13:13:276061// Tests that when multiple HPKP headers are present, asserting different
6062// policies, that only the first such policy is processed.
6063TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556064 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6065 https_test_server.SetSSLConfig(
6066 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6067 https_test_server.ServeFilesFromSourceDirectory(
6068 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276069 ASSERT_TRUE(https_test_server.Start());
6070
tommycli59a63432015-11-06 00:10:556071 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166072
[email protected]37fd55fb2013-06-29 13:13:276073 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196074 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556075 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:366076 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196077 request->Start();
[email protected]255620da2013-08-19 13:14:296078 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276079
6080 TransportSecurityState* security_state =
6081 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406082 TransportSecurityState::STSState sts_state;
6083 TransportSecurityState::PKPState pkp_state;
6084 EXPECT_TRUE(
6085 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6086 EXPECT_TRUE(
6087 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6088 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6089 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036090#if defined(OS_ANDROID)
6091 // Android's CertVerifyProc does not (yet) handle pins.
6092#else
martijnc0d6b622015-06-30 19:14:406093 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036094#endif
martijnc0d6b622015-06-30 19:14:406095 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276096
martijnc0d6b622015-06-30 19:14:406097 EXPECT_TRUE(sts_state.include_subdomains);
6098 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276099}
6100
tommycli59a63432015-11-06 00:10:556101#endif // !defined(OS_IOS)
6102
[email protected]316c1e5e2012-09-12 15:17:446103TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:556104 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446105
6106 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196107 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556108 http_test_server()->GetURL("/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366109 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196110 req->Start();
[email protected]255620da2013-08-19 13:14:296111 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446112
6113 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196114 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446115 EXPECT_EQ("text/html", mime_type);
6116
6117 std::string charset;
[email protected]f7022f32014-08-21 16:32:196118 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446119 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196120 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446121}
6122
[email protected]02494ec2014-05-07 15:05:296123TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346124 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346125 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346126 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026127 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346128
6129 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506130 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346131}
6132
[email protected]02494ec2014-05-07 15:05:296133#if !defined(DISABLE_FILE_SUPPORT)
6134TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6135 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6136 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456137 FileProtocolHandler file_protocol_handler(
6138 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296139 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6140
6141 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506142 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296143}
6144
[email protected]588614c22013-08-16 00:09:026145TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:556146 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446147
6148 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196149 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556150 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366151 &d));
[email protected]f7022f32014-08-21 16:32:196152 req->Start();
[email protected]255620da2013-08-19 13:14:296153 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446154
[email protected]f7022f32014-08-21 16:32:196155 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6156 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446157}
[email protected]02494ec2014-05-07 15:05:296158#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446159
[email protected]588614c22013-08-16 00:09:026160TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:556161 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:026162
6163 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196164 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556165 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366166 &d));
[email protected]f7022f32014-08-21 16:32:196167 req->Start();
[email protected]588614c22013-08-16 00:09:026168 base::MessageLoop::current()->Run();
6169
[email protected]f7022f32014-08-21 16:32:196170 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6171 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:026172}
6173
[email protected]316c1e5e2012-09-12 15:17:446174TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:556175 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446176
6177 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196178 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556179 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366180 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196181 req->Start();
[email protected]255620da2013-08-19 13:14:296182 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446183
[email protected]f7022f32014-08-21 16:32:196184 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6185 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446186}
6187
[email protected]e50efea2014-03-24 18:41:006188// Make sure redirects are cached, despite not reading their bodies.
6189TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:556190 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006191 GURL redirect_url =
tommycli59a63432015-11-06 00:10:556192 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:006193
6194 {
6195 TestDelegate d;
davidben151423e2015-03-23 18:48:366196 scoped_ptr<URLRequest> req(
6197 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196198 req->Start();
[email protected]e50efea2014-03-24 18:41:006199 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196200 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006201 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:556202 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006203 }
6204
6205 {
6206 TestDelegate d;
6207 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:366208 scoped_ptr<URLRequest> req(
6209 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196210 req->Start();
[email protected]e50efea2014-03-24 18:41:006211 base::RunLoop().Run();
6212
6213 EXPECT_EQ(1, d.received_redirect_count());
6214 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196215 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006216
[email protected]f7022f32014-08-21 16:32:196217 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006218 base::RunLoop().Run();
6219 EXPECT_EQ(1, d.received_redirect_count());
6220 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196221 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
tommycli59a63432015-11-06 00:10:556222 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006223 }
6224}
6225
6226// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6227// when the headers are read, since the body won't have been read.
6228TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:556229 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006230 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:556231 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:006232
6233 {
6234 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:556235 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:006236 default_network_delegate_.set_redirect_on_headers_received_url(
6237 redirect_to_url);
6238
6239 TestDelegate d;
davidben151423e2015-03-23 18:48:366240 scoped_ptr<URLRequest> req(
6241 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196242 req->Start();
[email protected]e50efea2014-03-24 18:41:006243 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196244 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006245 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196246 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006247 }
6248
6249 {
6250 TestDelegate d;
davidben151423e2015-03-23 18:48:366251 scoped_ptr<URLRequest> req(
6252 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196253 req->Start();
[email protected]e50efea2014-03-24 18:41:006254 base::RunLoop().Run();
6255
[email protected]f7022f32014-08-21 16:32:196256 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6257 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006258 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196259 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006260 }
6261}
6262
[email protected]5f714132014-03-26 10:41:166263// Tests that redirection to an unsafe URL is allowed when it has been marked as
6264// safe.
6265TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:556266 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166267
6268 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6269 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6270 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6271
6272 TestDelegate d;
6273 {
[email protected]f7022f32014-08-21 16:32:196274 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556275 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166276
[email protected]f7022f32014-08-21 16:32:196277 r->Start();
[email protected]5f714132014-03-26 10:41:166278 base::RunLoop().Run();
6279
[email protected]f7022f32014-08-21 16:32:196280 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:166281
[email protected]f7022f32014-08-21 16:32:196282 EXPECT_EQ(2U, r->url_chain().size());
6283 EXPECT_EQ(OK, r->status().error());
6284 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166285 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6286 }
6287}
6288
6289// Tests that a redirect to a different unsafe URL is blocked, even after adding
6290// some other URL to the whitelist.
6291TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:556292 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166293
6294 GURL unsafe_url("data:text/html,something");
6295 GURL different_unsafe_url("data:text/html,something-else");
6296 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6297 default_network_delegate_.set_allowed_unsafe_redirect_url(
6298 different_unsafe_url);
6299
6300 TestDelegate d;
6301 {
[email protected]f7022f32014-08-21 16:32:196302 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556303 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166304
[email protected]f7022f32014-08-21 16:32:196305 r->Start();
[email protected]5f714132014-03-26 10:41:166306 base::RunLoop().Run();
6307
[email protected]f7022f32014-08-21 16:32:196308 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
6309 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:166310 }
6311}
6312
[email protected]5f714132014-03-26 10:41:166313// Redirects from an URL with fragment to an unsafe URL with fragment should
6314// be allowed, and the reference fragment of the target URL should be preserved.
6315TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:556316 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166317
tommycli59a63432015-11-06 00:10:556318 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:166319 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6320 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6321
6322 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6323 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6324
6325 TestDelegate d;
6326 {
davidben151423e2015-03-23 18:48:366327 scoped_ptr<URLRequest> r(
6328 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166329
[email protected]f7022f32014-08-21 16:32:196330 r->Start();
[email protected]5f714132014-03-26 10:41:166331 base::RunLoop().Run();
6332
[email protected]f7022f32014-08-21 16:32:196333 EXPECT_EQ(2U, r->url_chain().size());
6334 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6335 EXPECT_EQ(OK, r->status().error());
6336 EXPECT_EQ(original_url, r->original_url());
6337 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166338 }
6339}
6340
6341// When a delegate has specified a safe redirect URL, but it does not match the
6342// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146343TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:556344 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166345
tommycli59a63432015-11-06 00:10:556346 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166347 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:556348 GURL redirect_url(http_test_server()->GetURL("/target"));
6349 GURL expected_redirect_url(
6350 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166351
6352 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6353 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6354
6355 TestDelegate d;
6356 {
davidben151423e2015-03-23 18:48:366357 scoped_ptr<URLRequest> r(
6358 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166359
[email protected]f7022f32014-08-21 16:32:196360 r->Start();
[email protected]5f714132014-03-26 10:41:166361 base::RunLoop().Run();
6362
[email protected]f7022f32014-08-21 16:32:196363 EXPECT_EQ(2U, r->url_chain().size());
6364 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6365 EXPECT_EQ(OK, r->status().error());
6366 EXPECT_EQ(original_url, r->original_url());
6367 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166368 }
6369}
6370
[email protected]f878230e2014-04-03 15:36:146371// When a delegate has specified a safe redirect URL, assume that the redirect
6372// URL should not be changed. In particular, the reference fragment should not
6373// be modified.
6374TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556375 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146376
tommycli59a63432015-11-06 00:10:556377 GURL original_url(
6378 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:146379 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6380
6381 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6382 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6383
6384 TestDelegate d;
6385 {
davidben151423e2015-03-23 18:48:366386 scoped_ptr<URLRequest> r(
6387 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146388
[email protected]f7022f32014-08-21 16:32:196389 r->Start();
[email protected]f878230e2014-04-03 15:36:146390 base::RunLoop().Run();
6391
[email protected]f7022f32014-08-21 16:32:196392 EXPECT_EQ(2U, r->url_chain().size());
6393 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6394 EXPECT_EQ(OK, r->status().error());
6395 EXPECT_EQ(original_url, r->original_url());
6396 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146397 }
6398}
6399
6400// When a URLRequestRedirectJob is created, the redirection must be followed and
6401// the reference fragment of the target URL must not be modified.
6402TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556403 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146404
tommycli59a63432015-11-06 00:10:556405 GURL original_url(
6406 http_test_server()->GetURL("/original#should-not-be-appended"));
6407 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:146408
6409 TestDelegate d;
davidben151423e2015-03-23 18:48:366410 scoped_ptr<URLRequest> r(
6411 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146412
mmenkeed0498b2015-12-08 23:20:426413 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196414 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:426415 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
6416 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:146417
[email protected]f7022f32014-08-21 16:32:196418 r->Start();
[email protected]f878230e2014-04-03 15:36:146419 base::RunLoop().Run();
6420
[email protected]f7022f32014-08-21 16:32:196421 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6422 EXPECT_EQ(OK, r->status().error());
6423 EXPECT_EQ(original_url, r->original_url());
6424 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146425}
6426
[email protected]316c1e5e2012-09-12 15:17:446427TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:556428 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446429
6430 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196431 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556432 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196433 req->SetReferrer("http://user:[email protected]/");
6434 req->Start();
[email protected]255620da2013-08-19 13:14:296435 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446436
6437 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6438}
6439
[email protected]99ecf6e2013-04-10 22:46:136440TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:556441 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136442
6443 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196444 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556445 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196446 req->SetReferrer("http://foo.com/test#fragment");
6447 req->Start();
[email protected]255620da2013-08-19 13:14:296448 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136449
6450 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6451}
6452
6453TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:556454 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136455
6456 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196457 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556458 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196459 req->SetReferrer("http://foo.com/test#fragment");
6460 req->SetReferrer("");
6461 req->Start();
[email protected]255620da2013-08-19 13:14:296462 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136463
6464 EXPECT_EQ(std::string("None"), d.data_received());
6465}
6466
[email protected]1826a402014-01-08 15:40:486467// Defer network start and then resume, checking that the request was a success
6468// and bytes were received.
6469TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556470 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486471
6472 TestDelegate d;
6473 {
6474 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556475 GURL test_url(http_test_server()->GetURL("/echo"));
davidben151423e2015-03-23 18:48:366476 scoped_ptr<URLRequest> req(
6477 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486478
[email protected]f7022f32014-08-21 16:32:196479 req->Start();
[email protected]1826a402014-01-08 15:40:486480 base::RunLoop().Run();
6481
6482 EXPECT_EQ(1, d.received_before_network_start_count());
6483 EXPECT_EQ(0, d.response_started_count());
6484
[email protected]f7022f32014-08-21 16:32:196485 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486486 base::RunLoop().Run();
6487
6488 EXPECT_EQ(1, d.response_started_count());
6489 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196490 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486491 }
6492}
6493
6494// Check that OnBeforeNetworkStart is only called once even if there is a
6495// redirect.
6496TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
tommycli59a63432015-11-06 00:10:556497 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486498
6499 TestDelegate d;
6500 {
6501 d.set_quit_on_redirect(true);
6502 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:196503 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556504 http_test_server()->GetURL("/server-redirect?echo"), DEFAULT_PRIORITY,
6505 &d));
[email protected]1826a402014-01-08 15:40:486506
[email protected]f7022f32014-08-21 16:32:196507 req->Start();
[email protected]1826a402014-01-08 15:40:486508 base::RunLoop().Run();
6509
6510 EXPECT_EQ(1, d.received_before_network_start_count());
6511 EXPECT_EQ(0, d.response_started_count());
6512 EXPECT_EQ(0, d.received_redirect_count());
6513
[email protected]f7022f32014-08-21 16:32:196514 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486515 base::RunLoop().Run();
6516
6517 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196518 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:486519 base::RunLoop().Run();
6520
6521 // Check that the redirect's new network transaction does not get propagated
6522 // to a second OnBeforeNetworkStart() notification.
6523 EXPECT_EQ(1, d.received_before_network_start_count());
6524
6525 EXPECT_EQ(1, d.response_started_count());
6526 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196527 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486528 }
6529}
6530
6531// Cancel the request after learning that the request would use the network.
6532TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556533 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486534
6535 TestDelegate d;
6536 {
6537 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556538 GURL test_url(http_test_server()->GetURL("/echo"));
davidben151423e2015-03-23 18:48:366539 scoped_ptr<URLRequest> req(
6540 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486541
[email protected]f7022f32014-08-21 16:32:196542 req->Start();
[email protected]1826a402014-01-08 15:40:486543 base::RunLoop().Run();
6544
6545 EXPECT_EQ(1, d.received_before_network_start_count());
6546 EXPECT_EQ(0, d.response_started_count());
6547
[email protected]f7022f32014-08-21 16:32:196548 req->Cancel();
[email protected]1826a402014-01-08 15:40:486549 base::RunLoop().Run();
6550
6551 EXPECT_EQ(1, d.response_started_count());
6552 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196553 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:486554 }
6555}
6556
[email protected]316c1e5e2012-09-12 15:17:446557TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:556558 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446559
6560 TestDelegate d;
6561 {
6562 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:196563 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556564 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6565 &d));
[email protected]f7022f32014-08-21 16:32:196566 req->Start();
[email protected]255620da2013-08-19 13:14:296567 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446568
6569 EXPECT_EQ(1, d.response_started_count());
6570 EXPECT_EQ(0, d.bytes_received());
6571 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196572 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446573 }
6574}
6575
6576TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:556577 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446578
6579 TestDelegate d;
6580 {
6581 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556582 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
davidben151423e2015-03-23 18:48:366583 scoped_ptr<URLRequest> req(
6584 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046585
[email protected]f7022f32014-08-21 16:32:196586 req->Start();
[email protected]255620da2013-08-19 13:14:296587 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446588
6589 EXPECT_EQ(1, d.received_redirect_count());
6590
[email protected]f7022f32014-08-21 16:32:196591 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296592 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446593
6594 EXPECT_EQ(1, d.response_started_count());
6595 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196596 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446597
[email protected]6cdfd7f2013-02-08 20:40:156598 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446599 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476600 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446601 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6602
6603 std::string contents;
[email protected]82f84b92013-08-30 18:23:506604 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446605 EXPECT_EQ(contents, d.data_received());
6606 }
6607}
6608
[email protected]79e1fd62013-06-20 06:50:046609TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:556610 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:046611
6612 TestDelegate d;
6613 {
6614 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556615 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
davidben151423e2015-03-23 18:48:366616 scoped_ptr<URLRequest> req(
6617 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046618
6619 EXPECT_FALSE(d.have_full_request_headers());
6620
[email protected]f7022f32014-08-21 16:32:196621 req->Start();
[email protected]255620da2013-08-19 13:14:296622 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046623
6624 EXPECT_EQ(1, d.received_redirect_count());
6625 EXPECT_TRUE(d.have_full_request_headers());
6626 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6627 d.ClearFullRequestHeaders();
6628
[email protected]f7022f32014-08-21 16:32:196629 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296630 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046631
tommycli59a63432015-11-06 00:10:556632 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:046633 EXPECT_EQ(1, d.response_started_count());
6634 EXPECT_TRUE(d.have_full_request_headers());
6635 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6636 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196637 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046638
6639 base::FilePath path;
6640 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476641 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046642 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6643
6644 std::string contents;
[email protected]82f84b92013-08-30 18:23:506645 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046646 EXPECT_EQ(contents, d.data_received());
6647 }
6648}
6649
[email protected]316c1e5e2012-09-12 15:17:446650TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:556651 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446652
6653 TestDelegate d;
6654 {
6655 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196656 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556657 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6658 &d));
[email protected]f7022f32014-08-21 16:32:196659 req->Start();
[email protected]255620da2013-08-19 13:14:296660 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446661
6662 EXPECT_EQ(1, d.received_redirect_count());
6663
[email protected]f7022f32014-08-21 16:32:196664 req->Cancel();
[email protected]255620da2013-08-19 13:14:296665 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446666
6667 EXPECT_EQ(1, d.response_started_count());
6668 EXPECT_EQ(0, d.bytes_received());
6669 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196670 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446671 }
6672}
6673
6674TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:556675 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446676
[email protected]3b23a222013-05-15 21:33:256677 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446678 {
6679 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196680 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556681 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6682 &d));
[email protected]316c1e5e2012-09-12 15:17:446683 HttpRequestHeaders headers;
6684 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196685 req->SetExtraRequestHeaders(headers);
6686 req->Start();
[email protected]255620da2013-08-19 13:14:296687 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256688
6689 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196690 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256691 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446692 }
6693
[email protected]3b23a222013-05-15 21:33:256694 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446695 {
6696 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196697 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556698 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6699 &d));
[email protected]316c1e5e2012-09-12 15:17:446700 HttpRequestHeaders headers;
6701 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196702 req->SetExtraRequestHeaders(headers);
6703 req->Start();
[email protected]255620da2013-08-19 13:14:296704 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446705
[email protected]f7022f32014-08-21 16:32:196706 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256707
6708 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196709 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256710 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446711 }
6712
[email protected]3b23a222013-05-15 21:33:256713 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446714 {
6715 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196716 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556717 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6718 &d));
[email protected]316c1e5e2012-09-12 15:17:446719 HttpRequestHeaders headers;
6720 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196721 req->SetExtraRequestHeaders(headers);
6722 req->Start();
[email protected]255620da2013-08-19 13:14:296723 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446724
[email protected]f7022f32014-08-21 16:32:196725 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256726
6727 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196728 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256729 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446730 }
6731}
6732
6733TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:556734 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446735
6736 // populate the cache
6737 {
6738 TestDelegate d;
6739 d.set_credentials(AuthCredentials(kUser, kSecret));
6740
[email protected]f7022f32014-08-21 16:32:196741 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556742 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196743 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446744
[email protected]255620da2013-08-19 13:14:296745 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446746
6747 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6748 }
6749
6750 // repeat request with end-to-end validation. since auth-basic results in a
6751 // cachable page, we expect this test to result in a 304. in which case, the
6752 // response should be fetched from the cache.
6753 {
6754 TestDelegate d;
6755 d.set_credentials(AuthCredentials(kUser, kSecret));
6756
[email protected]f7022f32014-08-21 16:32:196757 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556758 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196759 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6760 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446761
[email protected]255620da2013-08-19 13:14:296762 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446763
6764 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6765
6766 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196767 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446768 }
6769}
6770
6771// Check that Set-Cookie headers in 401 responses are respected.
6772// http://crbug.com/6450
6773TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:556774 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446775
6776 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:556777 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:446778
6779 // Request a page that will give a 401 containing a Set-Cookie header.
6780 // Verify that when the transaction is restarted, it includes the new cookie.
6781 {
[email protected]ceefd7fd2012-11-29 00:36:246782 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446783 TestURLRequestContext context(true);
6784 context.set_network_delegate(&network_delegate);
6785 context.Init();
6786
6787 TestDelegate d;
6788 d.set_credentials(AuthCredentials(kUser, kSecret));
6789
davidben151423e2015-03-23 18:48:366790 scoped_ptr<URLRequest> r(
6791 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196792 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446793
[email protected]255620da2013-08-19 13:14:296794 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446795
6796 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6797
6798 // Make sure we sent the cookie in the restarted transaction.
6799 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6800 != std::string::npos);
6801 }
6802
6803 // Same test as above, except this time the restart is initiated earlier
6804 // (without user intervention since identity is embedded in the URL).
6805 {
[email protected]ceefd7fd2012-11-29 00:36:246806 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446807 TestURLRequestContext context(true);
6808 context.set_network_delegate(&network_delegate);
6809 context.Init();
6810
6811 TestDelegate d;
6812
6813 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186814 replacements.SetUsernameStr("user2");
6815 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446816 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6817
davidben151423e2015-03-23 18:48:366818 scoped_ptr<URLRequest> r(
6819 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196820 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446821
[email protected]255620da2013-08-19 13:14:296822 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446823
6824 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6825
6826 // Make sure we sent the cookie in the restarted transaction.
6827 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6828 != std::string::npos);
6829 }
6830}
6831
[email protected]58e32bb2013-01-21 18:23:256832// Tests that load timing works as expected with auth and the cache.
6833TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:556834 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:256835
6836 // populate the cache
6837 {
6838 TestDelegate d;
6839 d.set_credentials(AuthCredentials(kUser, kSecret));
6840
[email protected]f7022f32014-08-21 16:32:196841 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556842 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196843 r->Start();
[email protected]58e32bb2013-01-21 18:23:256844
[email protected]255620da2013-08-19 13:14:296845 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256846
6847 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6848
6849 LoadTimingInfo load_timing_info_before_auth;
6850 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6851 &load_timing_info_before_auth));
6852 TestLoadTimingNotReused(load_timing_info_before_auth,
6853 CONNECT_TIMING_HAS_DNS_TIMES);
6854
6855 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196856 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256857 // The test server does not support keep alive sockets, so the second
6858 // request with auth should use a new socket.
6859 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6860 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6861 load_timing_info.socket_log_id);
6862 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6863 load_timing_info.connect_timing.connect_start);
6864 }
6865
[email protected]3b23a222013-05-15 21:33:256866 // Repeat request with end-to-end validation. Since auth-basic results in a
6867 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256868 // response should be fetched from the cache.
6869 {
6870 TestDelegate d;
6871 d.set_credentials(AuthCredentials(kUser, kSecret));
6872
[email protected]f7022f32014-08-21 16:32:196873 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556874 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196875 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6876 r->Start();
[email protected]58e32bb2013-01-21 18:23:256877
[email protected]255620da2013-08-19 13:14:296878 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256879
6880 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6881
6882 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196883 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256884
[email protected]3b23a222013-05-15 21:33:256885 // Since there was a request that went over the wire, the load timing
6886 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256887 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196888 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256889 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256890 }
6891}
6892
[email protected]316c1e5e2012-09-12 15:17:446893// In this test, we do a POST which the server will 302 redirect.
6894// The subsequent transaction should use GET, and should not send the
6895// Content-Type header.
6896// http://code.google.com/p/chromium/issues/detail?id=843
6897TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:556898 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446899
6900 const char kData[] = "hello world";
6901
6902 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196903 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556904 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY,
6905 &d));
[email protected]f7022f32014-08-21 16:32:196906 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076907 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446908
6909 // Set headers (some of which are specific to the POST).
6910 HttpRequestHeaders headers;
6911 headers.AddHeadersFromString(
6912 "Content-Type: multipart/form-data; "
6913 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6914 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6915 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6916 "Accept-Language: en-US,en\r\n"
6917 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6918 "Content-Length: 11\r\n"
6919 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196920 req->SetExtraRequestHeaders(headers);
6921 req->Start();
[email protected]255620da2013-08-19 13:14:296922 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446923
6924 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196925 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446926 EXPECT_EQ("text/html", mime_type);
6927
6928 const std::string& data = d.data_received();
6929
6930 // Check that the post-specific headers were stripped:
6931 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6932 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6933 EXPECT_FALSE(ContainsString(data, "Origin:"));
6934
6935 // These extra request headers should not have been stripped.
6936 EXPECT_TRUE(ContainsString(data, "Accept:"));
6937 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6938 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6939}
6940
jww5fe460ff2015-03-28 00:22:516941// The following tests check that we handle mutating the request for HTTP
6942// redirects as expected.
6943// See https://crbug.com/56373, https://crbug.com/102130, and
6944// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:446945
6946TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:556947 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446948
tommycli59a63432015-11-06 00:10:556949 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:516950 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:556951 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:446952
6953 HTTPRedirectMethodTest(url, "POST", "GET", true);
6954 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6955 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516956
6957 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6958 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6959 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6960 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6961 std::string());
[email protected]316c1e5e2012-09-12 15:17:446962}
6963
6964TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:556965 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446966
tommycli59a63432015-11-06 00:10:556967 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:516968 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:556969 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:446970
6971 HTTPRedirectMethodTest(url, "POST", "GET", true);
6972 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6973 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516974
6975 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6976 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6977 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6978 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6979 std::string());
[email protected]316c1e5e2012-09-12 15:17:446980}
6981
6982TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:556983 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446984
tommycli59a63432015-11-06 00:10:556985 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:516986 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:556987 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:446988
6989 HTTPRedirectMethodTest(url, "POST", "GET", true);
6990 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6991 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516992
6993 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6994 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6995 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6996 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6997 std::string());
[email protected]316c1e5e2012-09-12 15:17:446998}
6999
7000TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:557001 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447002
tommycli59a63432015-11-06 00:10:557003 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:517004 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557005 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:447006
7007 HTTPRedirectMethodTest(url, "POST", "POST", true);
7008 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7009 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517010
7011 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7012 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7013 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7014 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:447015}
7016
[email protected]0a17aab32014-04-24 03:32:377017TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:557018 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377019
tommycli59a63432015-11-06 00:10:557020 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:517021 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557022 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:377023
7024 HTTPRedirectMethodTest(url, "POST", "POST", true);
7025 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7026 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517027
7028 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7029 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7030 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7031 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:377032}
7033
7034// Make sure that 308 responses without bodies are not treated as redirects.
7035// Certain legacy apis that pre-date the response code expect this behavior
7036// (Like Google Drive).
7037TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:557038 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377039
7040 TestDelegate d;
tommycli59a63432015-11-06 00:10:557041 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:377042
davidben151423e2015-03-23 18:48:367043 scoped_ptr<URLRequest> request(
7044 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:377045
[email protected]f7022f32014-08-21 16:32:197046 request->Start();
[email protected]0a17aab32014-04-24 03:32:377047 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197048 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
7049 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:377050 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197051 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:377052 EXPECT_EQ("This is not a redirect.", d.data_received());
7053}
7054
[email protected]f878230e2014-04-03 15:36:147055TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:557056 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147057
tommycli59a63432015-11-06 00:10:557058 GURL original_url(
7059 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
7060 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:147061
7062 TestDelegate d;
7063 {
davidben151423e2015-03-23 18:48:367064 scoped_ptr<URLRequest> r(
7065 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:147066
[email protected]f7022f32014-08-21 16:32:197067 r->Start();
[email protected]f878230e2014-04-03 15:36:147068 base::RunLoop().Run();
7069
[email protected]f7022f32014-08-21 16:32:197070 EXPECT_EQ(2U, r->url_chain().size());
7071 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7072 EXPECT_EQ(OK, r->status().error());
7073 EXPECT_EQ(original_url, r->original_url());
7074 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:147075 }
7076}
7077
[email protected]cba24642014-08-15 20:49:597078TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557079 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597080
tommycli59a63432015-11-06 00:10:557081 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597082 GURL first_party_url("http://example.com");
7083
7084 TestDelegate d;
7085 {
davidben151423e2015-03-23 18:48:367086 scoped_ptr<URLRequest> r(
7087 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197088 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:597089
[email protected]f7022f32014-08-21 16:32:197090 r->Start();
[email protected]cba24642014-08-15 20:49:597091 base::RunLoop().Run();
7092
[email protected]f7022f32014-08-21 16:32:197093 EXPECT_EQ(2U, r->url_chain().size());
7094 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7095 EXPECT_EQ(OK, r->status().error());
7096 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597097 }
7098}
7099
7100TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557101 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597102
tommycli59a63432015-11-06 00:10:557103 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597104 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:557105 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:597106
7107 TestDelegate d;
7108 {
davidben151423e2015-03-23 18:48:367109 scoped_ptr<URLRequest> r(
7110 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197111 r->set_first_party_for_cookies(original_first_party_url);
7112 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597113 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7114
[email protected]f7022f32014-08-21 16:32:197115 r->Start();
[email protected]cba24642014-08-15 20:49:597116 base::RunLoop().Run();
7117
[email protected]f7022f32014-08-21 16:32:197118 EXPECT_EQ(2U, r->url_chain().size());
7119 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7120 EXPECT_EQ(OK, r->status().error());
7121 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597122 }
7123}
7124
[email protected]316c1e5e2012-09-12 15:17:447125TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:557126 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447127
7128 const char kData[] = "hello world";
7129
7130 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197131 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557132 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197133 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077134 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447135 HttpRequestHeaders headers;
7136 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517137 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197138 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447139
mmenkeed0498b2015-12-08 23:20:427140 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557141 req.get(), &default_network_delegate_,
7142 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427143 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7144 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447145
[email protected]f7022f32014-08-21 16:32:197146 req->Start();
[email protected]255620da2013-08-19 13:14:297147 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197148 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447149}
7150
7151TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:557152 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447153
7154 const char kData[] = "hello world";
7155
7156 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197157 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557158 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197159 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077160 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447161 HttpRequestHeaders headers;
7162 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517163 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197164 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447165
mmenkeed0498b2015-12-08 23:20:427166 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557167 req.get(), &default_network_delegate_,
7168 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097169 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:427170 "Very Good Reason"));
7171 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447172
[email protected]f7022f32014-08-21 16:32:197173 req->Start();
[email protected]255620da2013-08-19 13:14:297174 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197175 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447176 EXPECT_EQ(kData, d.data_received());
7177}
7178
7179// Check that default A-L header is sent.
7180TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557181 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447182
[email protected]8790210c2013-12-02 05:29:537183 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247184 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447185 TestURLRequestContext context(true);
7186 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437187 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447188 context.Init();
7189
7190 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197191 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557192 http_test_server()->GetURL("/echoheader?Accept-Language"),
7193 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197194 req->Start();
[email protected]255620da2013-08-19 13:14:297195 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447196 EXPECT_EQ("en", d.data_received());
7197}
7198
7199// Check that an empty A-L header is not sent. http://crbug.com/77365.
7200TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557201 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447202
[email protected]8790210c2013-12-02 05:29:537203 std::string empty_string; // Avoid most vexing parse on line below.
7204 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247205 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447206 TestURLRequestContext context(true);
7207 context.set_network_delegate(&network_delegate);
7208 context.Init();
7209 // We override the language after initialization because empty entries
7210 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437211 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447212
7213 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197214 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557215 http_test_server()->GetURL("/echoheader?Accept-Language"),
7216 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197217 req->Start();
[email protected]255620da2013-08-19 13:14:297218 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447219 EXPECT_EQ("None", d.data_received());
7220}
7221
7222// Check that if request overrides the A-L header, the default is not appended.
7223// See http://crbug.com/20894
7224TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557225 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447226
7227 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197228 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557229 http_test_server()->GetURL("/echoheader?Accept-Language"),
7230 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447231 HttpRequestHeaders headers;
7232 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197233 req->SetExtraRequestHeaders(headers);
7234 req->Start();
[email protected]255620da2013-08-19 13:14:297235 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447236 EXPECT_EQ(std::string("ru"), d.data_received());
7237}
7238
7239// Check that default A-E header is sent.
7240TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557241 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447242
7243 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197244 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557245 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7246 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447247 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197248 req->SetExtraRequestHeaders(headers);
7249 req->Start();
[email protected]255620da2013-08-19 13:14:297250 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447251 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7252}
7253
7254// Check that if request overrides the A-E header, the default is not appended.
7255// See http://crbug.com/47381
7256TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557257 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447258
7259 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197260 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557261 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7262 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447263 HttpRequestHeaders headers;
7264 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197265 req->SetExtraRequestHeaders(headers);
7266 req->Start();
[email protected]255620da2013-08-19 13:14:297267 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447268 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7269 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7270}
7271
[email protected]84f05432013-03-15 01:00:127272// Check that setting the A-C header sends the proper header.
7273TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:557274 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447275
7276 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197277 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557278 http_test_server()->GetURL("/echoheader?Accept-Charset"),
7279 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447280 HttpRequestHeaders headers;
7281 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197282 req->SetExtraRequestHeaders(headers);
7283 req->Start();
[email protected]255620da2013-08-19 13:14:297284 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447285 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7286}
7287
7288// Check that default User-Agent header is sent.
7289TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:557290 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447291
7292 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197293 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557294 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7295 &d));
[email protected]f7022f32014-08-21 16:32:197296 req->Start();
[email protected]255620da2013-08-19 13:14:297297 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197298 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377299 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447300}
7301
7302// Check that if request overrides the User-Agent header,
7303// the default is not appended.
marqf14fff8d2015-12-02 15:52:297304// TODO(crbug.com/564656) This test is flaky on iOS.
7305#if defined(OS_IOS)
7306#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
7307#else
7308#define MAYBE_OverrideUserAgent OverrideUserAgent
7309#endif
7310TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:557311 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447312
7313 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197314 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557315 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7316 &d));
[email protected]316c1e5e2012-09-12 15:17:447317 HttpRequestHeaders headers;
7318 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197319 req->SetExtraRequestHeaders(headers);
7320 req->Start();
[email protected]255620da2013-08-19 13:14:297321 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357322 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447323}
7324
[email protected]ee4c30d2012-11-07 15:08:437325// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7326// User-Agent header to be sent but does not send the Accept-Language and
7327// Accept-Charset headers.
7328TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:557329 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:437330
[email protected]ceefd7fd2012-11-29 00:36:247331 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437332 TestURLRequestContext context(true);
7333 context.set_network_delegate(&network_delegate);
7334 context.Init();
7335 // We override the HttpUserAgentSettings after initialization because empty
7336 // entries get overridden by Init().
7337 context.set_http_user_agent_settings(NULL);
7338
7339 struct {
7340 const char* request;
7341 const char* expected_response;
tommycli59a63432015-11-06 00:10:557342 } tests[] = {{"/echoheader?Accept-Language", "None"},
7343 {"/echoheader?Accept-Charset", "None"},
7344 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:437345
viettrungluue4a8b882014-10-16 06:17:387346 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437347 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197348 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557349 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197350 req->Start();
[email protected]255620da2013-08-19 13:14:297351 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437352 EXPECT_EQ(tests[i].expected_response, d.data_received())
7353 << " Request = \"" << tests[i].request << "\"";
7354 }
7355}
7356
[email protected]5033ab82013-03-22 20:17:467357// Make sure that URLRequest passes on its priority updates to
7358// newly-created jobs after the first one.
7359TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:557360 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:467361
7362 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197363 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557364 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197365 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467366
mmenkeed0498b2015-12-08 23:20:427367 scoped_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557368 req.get(), &default_network_delegate_,
7369 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427370 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7371 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:467372
[email protected]f7022f32014-08-21 16:32:197373 req->SetPriority(LOW);
7374 req->Start();
7375 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467376
mmenkeed0498b2015-12-08 23:20:427377 RequestPriority job_priority;
7378 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
7379 req.get(), &default_network_delegate_, &job_priority));
7380 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:467381
7382 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297383 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:427384 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:467385}
7386
[email protected]80abdad2014-03-15 00:20:547387// Check that creating a network request while entering/exiting suspend mode
7388// fails as it should. This is the only case where an HttpTransactionFactory
7389// does not return an HttpTransaction.
7390TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7391 // Create a new HttpNetworkLayer that thinks it's suspended.
mmenke2281f3762015-11-02 20:38:177392 scoped_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
7393 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547394 network_layer->OnSuspend();
7395
mmenkebc31a2c2015-10-29 13:44:457396 HttpCache http_cache(network_layer.Pass(),
mmenkee65e7af2015-10-13 17:16:427397 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547398
7399 TestURLRequestContext context(true);
7400 context.set_http_transaction_factory(&http_cache);
7401 context.Init();
7402
7403 TestDelegate d;
davidben151423e2015-03-23 18:48:367404 scoped_ptr<URLRequest> req(
7405 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197406 req->Start();
[email protected]80abdad2014-03-15 00:20:547407 base::RunLoop().Run();
7408
7409 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197410 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7411 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547412}
7413
mmenke2281f3762015-11-02 20:38:177414namespace {
[email protected]80abdad2014-03-15 00:20:547415
mmenke2281f3762015-11-02 20:38:177416// HttpTransactionFactory that synchronously fails to create transactions.
7417class FailingHttpTransactionFactory : public HttpTransactionFactory {
7418 public:
7419 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7420 : network_session_(network_session) {}
7421
7422 ~FailingHttpTransactionFactory() override {}
7423
7424 // HttpTransactionFactory methods:
7425 int CreateTransaction(RequestPriority priority,
7426 scoped_ptr<HttpTransaction>* trans) override {
7427 return ERR_FAILED;
7428 }
7429
7430 HttpCache* GetCache() override { return nullptr; }
7431
7432 HttpNetworkSession* GetSession() override { return network_session_; }
7433
7434 private:
7435 HttpNetworkSession* network_session_;
7436
7437 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7438};
7439
7440} // namespace
7441
7442// Check that when a request that fails to create an HttpTransaction can be
7443// cancelled while the failure notification is pending, and doesn't send two
7444// failure notifications.
7445//
7446// This currently only happens when in suspend mode and there's no cache, but
7447// just use a special HttpTransactionFactory, to avoid depending on those
7448// behaviors.
7449TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7450 FailingHttpTransactionFactory http_transaction_factory(
7451 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547452 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177453 context.set_http_transaction_factory(&http_transaction_factory);
7454 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547455 context.Init();
7456
7457 TestDelegate d;
davidben151423e2015-03-23 18:48:367458 scoped_ptr<URLRequest> req(
7459 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177460 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7461 // try to create an HttpNetworkTransaction synchronously on start).
7462 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197463 req->Start();
mmenke2281f3762015-11-02 20:38:177464 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547465 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177466 // Run pending error task, if there is one.
7467 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547468
7469 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177470 EXPECT_EQ(1, d.response_started_count());
7471 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
7472
7473 // NetworkDelegate should see the cancellation, but not the error.
7474 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7475 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547476}
7477
ttuttlec0c828492015-05-15 01:25:557478TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:557479 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557480
7481 TestDelegate d;
tommycli59a63432015-11-06 00:10:557482 GURL test_url(http_test_server()->GetURL("/"));
ttuttlec0c828492015-05-15 01:25:557483 scoped_ptr<URLRequest> req(
7484 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7485
7486 req->Start();
7487 base::RunLoop().Run();
7488
7489 EXPECT_TRUE(req->response_info().network_accessed);
7490}
7491
7492TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:557493 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557494
7495 // Populate the cache.
7496 TestDelegate d;
7497 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557498 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
ttuttlec0c828492015-05-15 01:25:557499 req->Start();
7500 base::RunLoop().Run();
7501
7502 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7503 EXPECT_TRUE(req->response_info().network_accessed);
7504 EXPECT_FALSE(req->response_info().was_cached);
7505
tommycli59a63432015-11-06 00:10:557506 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
ttuttlec0c828492015-05-15 01:25:557507 DEFAULT_PRIORITY, &d);
7508 req->Start();
7509 base::RunLoop().Run();
7510
7511 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7512 EXPECT_FALSE(req->response_info().network_accessed);
7513 EXPECT_TRUE(req->response_info().was_cached);
7514}
7515
7516TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:557517 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557518
7519 TestDelegate d;
tommycli59a63432015-11-06 00:10:557520 GURL test_url(http_test_server()->GetURL("/"));
ttuttlec0c828492015-05-15 01:25:557521 scoped_ptr<URLRequest> req(
7522 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7523 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7524
7525 req->Start();
7526 base::RunLoop().Run();
7527
7528 EXPECT_FALSE(req->response_info().network_accessed);
7529}
7530
bengr1bf8e942014-11-07 01:36:507531class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7532 public:
7533 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7534 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7535 // tests into the factory tests.
7536 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7537 }
7538
7539 void SetUpFactory() override {
7540 interceptor_ = new MockURLRequestInterceptor();
7541 job_factory_.reset(new URLRequestInterceptingJobFactory(
7542 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
7543 }
7544
7545 MockURLRequestInterceptor* interceptor() const {
7546 return interceptor_;
7547 }
7548
7549 private:
7550 MockURLRequestInterceptor* interceptor_;
7551};
7552
7553TEST_F(URLRequestInterceptorTestHTTP,
7554 NetworkDelegateNotificationOnRedirectIntercept) {
7555 interceptor()->set_intercept_redirect(true);
7556 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7557 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7558
tommycli59a63432015-11-06 00:10:557559 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507560
7561 TestDelegate d;
7562 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557563 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507564 req->Start();
7565 base::RunLoop().Run();
7566
7567 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7568 // Check we got one good response
7569 EXPECT_TRUE(req->status().is_success());
7570 if (req->status().is_success())
7571 EXPECT_EQ(200, req->response_headers()->response_code());
7572
7573 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7574 EXPECT_EQ(1, d.response_started_count());
7575 EXPECT_EQ(0, d.received_redirect_count());
7576
7577 EXPECT_EQ(1, default_network_delegate()->created_requests());
7578 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7579 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7580}
7581
7582TEST_F(URLRequestInterceptorTestHTTP,
7583 NetworkDelegateNotificationOnErrorIntercept) {
7584 // Intercept that error and respond with an OK response.
7585 interceptor()->set_intercept_final_response(true);
7586 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7587 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7588 default_network_delegate()->set_can_be_intercepted_on_error(true);
7589
tommycli59a63432015-11-06 00:10:557590 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507591
7592 TestDelegate d;
7593 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557594 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:367595 &d));
bengr1bf8e942014-11-07 01:36:507596 req->set_method("GET");
7597 req->Start();
7598 base::RunLoop().Run();
7599
7600 EXPECT_TRUE(interceptor()->did_intercept_final());
7601
7602 // Check we received one good response.
7603 EXPECT_TRUE(req->status().is_success());
7604 if (req->status().is_success())
7605 EXPECT_EQ(200, req->response_headers()->response_code());
7606 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7607 EXPECT_EQ(1, d.response_started_count());
7608 EXPECT_EQ(0, d.received_redirect_count());
7609
7610 EXPECT_EQ(1, default_network_delegate()->created_requests());
7611 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7612 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7613}
7614
7615TEST_F(URLRequestInterceptorTestHTTP,
7616 NetworkDelegateNotificationOnResponseIntercept) {
7617 // Intercept that error and respond with an OK response.
7618 interceptor()->set_intercept_final_response(true);
7619
7620 // Intercept with a real URLRequestHttpJob.
7621 interceptor()->set_use_url_request_http_job(true);
7622
tommycli59a63432015-11-06 00:10:557623 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507624
7625 TestDelegate d;
7626 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557627 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507628 req->set_method("GET");
7629 req->Start();
7630 base::RunLoop().Run();
7631
7632 EXPECT_TRUE(interceptor()->did_intercept_final());
7633
7634 // Check we received one good response.
7635 EXPECT_TRUE(req->status().is_success());
7636 if (req->status().is_success())
7637 EXPECT_EQ(200, req->response_headers()->response_code());
7638 EXPECT_EQ("hello", d.data_received());
7639 EXPECT_EQ(1, d.response_started_count());
7640 EXPECT_EQ(0, d.received_redirect_count());
7641
7642 EXPECT_EQ(1, default_network_delegate()->created_requests());
7643 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7644 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7645}
7646
mkwst0c5eab872014-11-21 14:18:547647class URLRequestTestReferrerPolicy : public URLRequestTest {
7648 public:
7649 URLRequestTestReferrerPolicy() {}
7650
tommycli59a63432015-11-06 00:10:557651 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
7652 origin_server_.reset(new EmbeddedTestServer(type));
7653 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
7654 origin_server_->AddDefaultHandlers(
7655 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7656 } else {
7657 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7658 }
mkwst0c5eab872014-11-21 14:18:547659 ASSERT_TRUE(origin_server_->Start());
7660 }
7661
tommycli59a63432015-11-06 00:10:557662 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
7663 net::EmbeddedTestServer::Type dest_type) {
7664 origin_server_.reset(new EmbeddedTestServer(origin_type));
7665 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7666 origin_server_->AddDefaultHandlers(
7667 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7668 } else {
7669 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7670 }
mkwst0c5eab872014-11-21 14:18:547671 ASSERT_TRUE(origin_server_->Start());
7672
tommycli59a63432015-11-06 00:10:557673 destination_server_.reset(new EmbeddedTestServer(dest_type));
7674 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7675 destination_server_->AddDefaultHandlers(
7676 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7677 } else {
7678 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7679 }
mkwst0c5eab872014-11-21 14:18:547680 ASSERT_TRUE(destination_server_->Start());
7681 }
7682
7683 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7684 const GURL& referrer,
7685 const GURL& expected) {
7686 // Create and execute the request: we'll only have a |destination_server_|
7687 // if the origins are meant to be distinct. Otherwise, we'll use the
7688 // |origin_server_| for both endpoints.
7689 GURL destination_url =
tommycli59a63432015-11-06 00:10:557690 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
7691 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:547692 GURL origin_url =
tommycli59a63432015-11-06 00:10:557693 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:547694
7695 TestDelegate d;
7696 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367697 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547698 req->set_referrer_policy(policy);
7699 req->SetReferrer(referrer.spec());
7700 req->Start();
7701 base::RunLoop().Run();
7702
7703 EXPECT_EQ(1, d.response_started_count());
7704 EXPECT_EQ(1, d.received_redirect_count());
7705 EXPECT_EQ(destination_url, req->url());
7706 EXPECT_TRUE(req->status().is_success());
7707 EXPECT_EQ(200, req->response_headers()->response_code());
7708
7709 EXPECT_EQ(expected.spec(), req->referrer());
7710 if (expected.is_empty())
7711 EXPECT_EQ("None", d.data_received());
7712 else
7713 EXPECT_EQ(expected.spec(), d.data_received());
7714 }
7715
tommycli59a63432015-11-06 00:10:557716 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:547717
7718 private:
tommycli59a63432015-11-06 00:10:557719 scoped_ptr<EmbeddedTestServer> origin_server_;
7720 scoped_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:547721};
7722
7723TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:557724 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547725
7726 VerifyReferrerAfterRedirect(
7727 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557728 origin_server()->GetURL("/path/to/file.html"),
7729 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547730
7731 VerifyReferrerAfterRedirect(
7732 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557733 origin_server()->GetURL("/path/to/file.html"),
7734 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547735
7736 VerifyReferrerAfterRedirect(
7737 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557738 origin_server()->GetURL("/path/to/file.html"),
7739 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547740
7741 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557742 origin_server()->GetURL("/path/to/file.html"),
7743 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547744}
7745
tommycli59a63432015-11-06 00:10:557746TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
7747 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
7748 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547749
7750 VerifyReferrerAfterRedirect(
7751 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557752 origin_server()->GetURL("/path/to/file.html"),
7753 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547754
7755 VerifyReferrerAfterRedirect(
7756 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557757 origin_server()->GetURL("/path/to/file.html"),
7758 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547759
7760 VerifyReferrerAfterRedirect(
7761 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557762 origin_server()->GetURL("/path/to/file.html"),
7763 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547764
7765 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557766 origin_server()->GetURL("/path/to/file.html"),
7767 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547768}
7769
7770TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:557771 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547772
7773 VerifyReferrerAfterRedirect(
7774 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557775 origin_server()->GetURL("/path/to/file.html"),
7776 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547777
7778 VerifyReferrerAfterRedirect(
7779 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557780 origin_server()->GetURL("/path/to/file.html"),
7781 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547782
7783 VerifyReferrerAfterRedirect(
7784 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557785 origin_server()->GetURL("/path/to/file.html"),
7786 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547787
7788 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557789 origin_server()->GetURL("/path/to/file.html"),
7790 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547791}
7792
tommycli59a63432015-11-06 00:10:557793TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7794 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
7795 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547796
7797 VerifyReferrerAfterRedirect(
7798 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557799 origin_server()->GetURL("/path/to/file.html"),
7800 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547801
7802 VerifyReferrerAfterRedirect(
7803 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557804 origin_server()->GetURL("/path/to/file.html"),
7805 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547806
7807 VerifyReferrerAfterRedirect(
7808 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557809 origin_server()->GetURL("/path/to/file.html"),
7810 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547811
7812 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557813 origin_server()->GetURL("/path/to/file.html"),
7814 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547815}
7816
tommycli59a63432015-11-06 00:10:557817TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7818 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
7819 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547820
7821 VerifyReferrerAfterRedirect(
7822 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557823 origin_server()->GetURL("/path/to/file.html"),
7824 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547825
7826 VerifyReferrerAfterRedirect(
7827 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557828 origin_server()->GetURL("/path/to/file.html"),
7829 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547830
7831 VerifyReferrerAfterRedirect(
7832 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557833 origin_server()->GetURL("/path/to/file.html"),
7834 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547835
7836 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557837 origin_server()->GetURL("/path/to/file.html"),
7838 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547839}
7840
tommycli59a63432015-11-06 00:10:557841TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7842 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
7843 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547844
7845 VerifyReferrerAfterRedirect(
7846 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557847 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:547848
7849 VerifyReferrerAfterRedirect(
7850 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557851 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:547852
7853 VerifyReferrerAfterRedirect(
7854 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557855 origin_server()->GetURL("/path/to/file.html"),
7856 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547857
7858 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557859 origin_server()->GetURL("/path/to/file.html"),
7860 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547861}
7862
[email protected]73e0bba2009-02-19 22:57:097863class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507864 public:
[email protected]ef2bf422012-05-11 03:27:097865 HTTPSRequestTest() : default_context_(true) {
7866 default_context_.set_network_delegate(&default_network_delegate_);
7867 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507868 }
dcheng67be2b1f2014-10-27 21:47:297869 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507870
7871 protected:
[email protected]ceefd7fd2012-11-29 00:36:247872 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097873 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467874};
7875
[email protected]c044616e2013-02-20 02:01:267876TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:557877 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7878 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:227879 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117880 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467881
[email protected]ea224582008-12-07 20:25:467882 TestDelegate d;
7883 {
[email protected]f7022f32014-08-21 16:32:197884 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557885 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197886 r->Start();
7887 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467888
[email protected]255620da2013-08-19 13:14:297889 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467890
7891 EXPECT_EQ(1, d.response_started_count());
7892 EXPECT_FALSE(d.received_data_before_response());
7893 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197894 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197895 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197896 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197897 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197898 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467899 }
[email protected]ea224582008-12-07 20:25:467900}
7901
[email protected]5774ada2010-07-15 06:30:547902TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:557903 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7904 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
7905 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:227906 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117907 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337908
7909 bool err_allowed = true;
7910 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7911 TestDelegate d;
7912 {
7913 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197914 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557915 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337916
[email protected]f7022f32014-08-21 16:32:197917 r->Start();
7918 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337919
[email protected]255620da2013-08-19 13:14:297920 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337921
7922 EXPECT_EQ(1, d.response_started_count());
7923 EXPECT_FALSE(d.received_data_before_response());
7924 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177925 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337926 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197927 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177928 } else {
[email protected]bacff652009-03-31 17:50:337929 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177930 }
[email protected]bacff652009-03-31 17:50:337931 }
7932 }
7933}
7934
[email protected]5774ada2010-07-15 06:30:547935TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:557936 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7937 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
7938 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:227939 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117940 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337941
7942 // Iterate from false to true, just so that we do the opposite of the
7943 // previous test in order to increase test coverage.
7944 bool err_allowed = false;
7945 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7946 TestDelegate d;
7947 {
7948 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197949 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557950 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337951
[email protected]f7022f32014-08-21 16:32:197952 r->Start();
7953 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337954
[email protected]255620da2013-08-19 13:14:297955 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337956
7957 EXPECT_EQ(1, d.response_started_count());
7958 EXPECT_FALSE(d.received_data_before_response());
7959 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177960 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337961 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197962 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177963 } else {
[email protected]bacff652009-03-31 17:50:337964 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177965 }
[email protected]bacff652009-03-31 17:50:337966 }
7967 }
7968}
[email protected]73e0bba2009-02-19 22:57:097969
tommycli59a63432015-11-06 00:10:557970// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
7971// security state. (see http://crbug.com/550977).
7972#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:447973// This tests that a load of www.google.com with a certificate error sets
7974// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7975// the interstitial to be fatal.
7976TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
tommycli59a63432015-11-06 00:10:557977 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7978 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
7979 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:447980 ASSERT_TRUE(test_server.Start());
7981
7982 // We require that the URL be www.google.com in order to pick up the
7983 // preloaded HSTS entries in the TransportSecurityState. This means that we
7984 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247985 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447986
7987 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247988 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447989 TestURLRequestContext context(true);
7990 context.set_network_delegate(&network_delegate);
7991 context.set_host_resolver(&host_resolver);
7992 TransportSecurityState transport_security_state;
7993 context.set_transport_security_state(&transport_security_state);
7994 context.Init();
7995
7996 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197997 scoped_ptr<URLRequest> r(context.CreateRequest(
7998 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367999 test_server.host_port_pair().port())),
8000 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448001
[email protected]f7022f32014-08-21 16:32:198002 r->Start();
8003 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448004
[email protected]255620da2013-08-19 13:14:298005 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448006
8007 EXPECT_EQ(1, d.response_started_count());
8008 EXPECT_FALSE(d.received_data_before_response());
8009 EXPECT_TRUE(d.have_certificate_errors());
8010 EXPECT_TRUE(d.certificate_errors_are_fatal());
8011}
8012
8013// This tests that cached HTTPS page loads do not cause any updates to the
8014// TransportSecurityState.
8015TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
8016 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
8017 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:558018 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8019 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8020 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448021 ASSERT_TRUE(test_server.Start());
8022
[email protected]9e6968d2014-05-07 21:46:268023 // We require that the URL be www.google.com in order to pick up the static
8024 // and dynamic STS and PKP entries in the TransportSecurityState. This means
8025 // that we have to use a MockHostResolver in order to direct www.google.com to
8026 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448027
8028 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248029 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448030 TestURLRequestContext context(true);
8031 context.set_network_delegate(&network_delegate);
8032 context.set_host_resolver(&host_resolver);
8033 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:268034
martijnc0d6b622015-06-30 19:14:408035 TransportSecurityState::STSState static_sts_state;
8036 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268037 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408038 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:448039 context.set_transport_security_state(&transport_security_state);
8040 context.Init();
8041
martijnc0d6b622015-06-30 19:14:408042 TransportSecurityState::STSState dynamic_sts_state;
8043 TransportSecurityState::PKPState dynamic_pkp_state;
8044 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
8045 &dynamic_sts_state));
8046 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
8047 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268048
[email protected]316c1e5e2012-09-12 15:17:448049 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198050 scoped_ptr<URLRequest> r(context.CreateRequest(
8051 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368052 test_server.host_port_pair().port())),
8053 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448054
[email protected]f7022f32014-08-21 16:32:198055 r->Start();
8056 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448057
[email protected]255620da2013-08-19 13:14:298058 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448059
8060 EXPECT_EQ(1, d.response_started_count());
8061 EXPECT_FALSE(d.received_data_before_response());
8062 EXPECT_TRUE(d.have_certificate_errors());
8063 EXPECT_TRUE(d.certificate_errors_are_fatal());
8064
[email protected]9e6968d2014-05-07 21:46:268065 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408066 TransportSecurityState::STSState new_static_sts_state;
8067 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268068 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408069 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8070 TransportSecurityState::STSState new_dynamic_sts_state;
8071 TransportSecurityState::PKPState new_dynamic_pkp_state;
8072 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8073 "www.google.com", &new_dynamic_sts_state));
8074 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8075 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268076
martijnc0d6b622015-06-30 19:14:408077 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8078 EXPECT_EQ(new_static_sts_state.include_subdomains,
8079 static_sts_state.include_subdomains);
8080 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8081 static_pkp_state.include_subdomains);
8082 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.spki_hashes,
8083 static_pkp_state.spki_hashes));
8084 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.bad_spki_hashes,
8085 static_pkp_state.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:448086}
8087
[email protected]8ccc69f2012-11-28 19:52:148088// Make sure HSTS preserves a POST request's method and body.
8089TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8090 static const char kData[] = "hello world";
8091
tommycli59a63432015-11-06 00:10:558092 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8093 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228094 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148095 ASSERT_TRUE(test_server.Start());
8096
8097
8098 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8099 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:558100 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:228101 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148102 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148103
8104 // Force https for www.somewhere.com.
8105 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208106 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8107 bool include_subdomains = false;
8108 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8109 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148110
8111 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8112
8113 TestURLRequestContext context(true);
8114 context.set_host_resolver(&host_resolver);
8115 context.set_transport_security_state(&transport_security_state);
8116 context.set_network_delegate(&network_delegate);
8117 context.Init();
8118
8119 TestDelegate d;
8120 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8121 // cause a certificate error. Ignore the error.
8122 d.set_allow_certificate_errors(true);
8123
[email protected]f7022f32014-08-21 16:32:198124 scoped_ptr<URLRequest> req(context.CreateRequest(
8125 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368126 test_server.host_port_pair().port())),
8127 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198128 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078129 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148130
[email protected]f7022f32014-08-21 16:32:198131 req->Start();
[email protected]255620da2013-08-19 13:14:298132 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148133
[email protected]f7022f32014-08-21 16:32:198134 EXPECT_EQ("https", req->url().scheme());
8135 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148136 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408137
8138 LoadTimingInfo load_timing_info;
8139 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8140 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8141 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148142}
8143
rob4e0be1f2014-09-11 23:40:228144// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8145TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8146 static const char kOriginHeaderValue[] = "http://www.example.com";
8147
tommycli59a63432015-11-06 00:10:558148 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8149 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:228150 ASSERT_TRUE(test_server.Start());
8151
8152 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8153 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:558154 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
8155 // default.
rob4e0be1f2014-09-11 23:40:228156 MockHostResolver host_resolver;
8157
8158 TransportSecurityState transport_security_state;
8159 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8160 bool include_subdomains = false;
8161 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8162
8163 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8164
8165 MockCertVerifier cert_verifier;
8166 cert_verifier.set_default_result(OK);
8167
8168 TestURLRequestContext context(true);
8169 context.set_host_resolver(&host_resolver);
8170 context.set_transport_security_state(&transport_security_state);
8171 context.set_network_delegate(&network_delegate);
8172 context.set_cert_verifier(&cert_verifier);
8173 context.Init();
8174
8175 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8176 test_server.host_port_pair().port()));
8177 url::Replacements<char> replacements;
8178 const char kNewScheme[] = "https";
8179 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8180 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8181
8182 TestDelegate d;
8183 // Quit on redirect to allow response header inspection upon redirect.
8184 d.set_quit_on_redirect(true);
8185
davidben151423e2015-03-23 18:48:368186 scoped_ptr<URLRequest> req(
8187 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228188 // Set Origin header to simulate a cross-origin request.
8189 HttpRequestHeaders request_headers;
8190 request_headers.SetHeader("Origin", kOriginHeaderValue);
8191 req->SetExtraRequestHeaders(request_headers);
8192
8193 req->Start();
8194 base::RunLoop().Run();
8195
8196 EXPECT_EQ(1, d.received_redirect_count());
8197
8198 const HttpResponseHeaders* headers = req->response_headers();
8199 std::string redirect_location;
8200 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8201 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8202
8203 std::string received_cors_header;
8204 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8205 &received_cors_header));
8206 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8207}
8208
Adam Ricecb76ac62015-02-20 05:33:258209// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
8210// are performed in net/websockets/websocket_end_to_end_test.cc.
8211TEST(WebSocketURLRequestTest, HSTSApplied) {
8212 TestNetworkDelegate network_delegate;
8213 TransportSecurityState transport_security_state;
8214 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8215 bool include_subdomains = false;
8216 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8217 TestURLRequestContext context(true);
8218 context.set_transport_security_state(&transport_security_state);
8219 context.set_network_delegate(&network_delegate);
8220 context.Init();
8221 GURL ws_url("ws://example.net/echo");
8222 TestDelegate delegate;
8223 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:368224 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:258225 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
8226 EXPECT_TRUE(ws_url.SchemeIs("wss"));
8227}
8228
[email protected]316c1e5e2012-09-12 15:17:448229namespace {
8230
8231class SSLClientAuthTestDelegate : public TestDelegate {
8232 public:
8233 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8234 }
dchengb03027d2014-10-21 12:00:208235 void OnCertificateRequested(URLRequest* request,
8236 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448237 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178238 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448239 }
8240 int on_certificate_requested_count() {
8241 return on_certificate_requested_count_;
8242 }
8243 private:
8244 int on_certificate_requested_count_;
8245};
8246
8247} // namespace
8248
8249// TODO(davidben): Test the rest of the code. Specifically,
8250// - Filtering which certificates to select.
8251// - Sending a certificate back.
8252// - Getting a certificate request in an SSL renegotiation sending the
8253// HTTP request.
8254TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:558255 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8256 net::SSLServerConfig ssl_config;
8257 ssl_config.require_client_cert = true;
8258 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
8259 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228260 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448261 ASSERT_TRUE(test_server.Start());
8262
8263 SSLClientAuthTestDelegate d;
8264 {
[email protected]f7022f32014-08-21 16:32:198265 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558266 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448267
[email protected]f7022f32014-08-21 16:32:198268 r->Start();
8269 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448270
[email protected]255620da2013-08-19 13:14:298271 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448272
8273 EXPECT_EQ(1, d.on_certificate_requested_count());
8274 EXPECT_FALSE(d.received_data_before_response());
8275 EXPECT_EQ(0, d.bytes_received());
8276
8277 // Send no certificate.
8278 // TODO(davidben): Get temporary client cert import (with keys) working on
8279 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:548280 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:448281
[email protected]255620da2013-08-19 13:14:298282 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448283
8284 EXPECT_EQ(1, d.response_started_count());
8285 EXPECT_FALSE(d.received_data_before_response());
8286 EXPECT_NE(0, d.bytes_received());
8287 }
8288}
8289
8290TEST_F(HTTPSRequestTest, ResumeTest) {
8291 // Test that we attempt a session resume when making two connections to the
8292 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228293 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448294 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228295 SpawnedTestServer test_server(
8296 SpawnedTestServer::TYPE_HTTPS,
8297 ssl_options,
8298 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448299 ASSERT_TRUE(test_server.Start());
8300
8301 SSLClientSocket::ClearSessionCache();
8302
8303 {
8304 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198305 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368306 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448307
[email protected]f7022f32014-08-21 16:32:198308 r->Start();
8309 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448310
[email protected]255620da2013-08-19 13:14:298311 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448312
8313 EXPECT_EQ(1, d.response_started_count());
8314 }
8315
8316 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8317 CloseAllConnections();
8318
8319 {
8320 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198321 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368322 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448323
[email protected]f7022f32014-08-21 16:32:198324 r->Start();
8325 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448326
[email protected]255620da2013-08-19 13:14:298327 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448328
8329 // The response will look like;
8330 // insert abc
8331 // lookup abc
8332 // insert xyz
8333 //
8334 // With a newline at the end which makes the split think that there are
8335 // four lines.
8336
8337 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298338 std::vector<std::string> lines = base::SplitString(
8339 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448340 ASSERT_EQ(4u, lines.size()) << d.data_received();
8341
8342 std::string session_id;
8343
8344 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298345 std::vector<std::string> parts = base::SplitString(
8346 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448347 ASSERT_EQ(2u, parts.size());
8348 if (i == 0) {
8349 EXPECT_EQ("insert", parts[0]);
8350 session_id = parts[1];
8351 } else {
8352 EXPECT_EQ("lookup", parts[0]);
8353 EXPECT_EQ(session_id, parts[1]);
8354 }
8355 }
8356 }
8357}
8358
Adam Langley32352ad2014-10-14 22:31:008359// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8360// the result of fetching "ssl-session-cache" from the test server, indicates
8361// that exactly two different sessions were inserted, with no lookups etc.
8362static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298363 std::vector<std::string> lines = base::SplitString(
8364 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008365 ASSERT_EQ(3u, lines.size()) << session_info;
8366
8367 std::string session_id;
8368 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298369 std::vector<std::string> parts = base::SplitString(
8370 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008371 ASSERT_EQ(2u, parts.size());
8372 EXPECT_EQ("insert", parts[0]);
8373 if (i == 0) {
8374 session_id = parts[1];
8375 } else {
8376 EXPECT_NE(session_id, parts[1]);
8377 }
8378 }
8379}
8380
[email protected]316c1e5e2012-09-12 15:17:448381TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8382 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8383 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228384 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448385 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228386 SpawnedTestServer test_server(
8387 SpawnedTestServer::TYPE_HTTPS,
8388 ssl_options,
8389 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448390 ASSERT_TRUE(test_server.Start());
8391
8392 SSLClientSocket::ClearSessionCache();
8393
8394 {
8395 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198396 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368397 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448398
[email protected]f7022f32014-08-21 16:32:198399 r->Start();
8400 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448401
[email protected]255620da2013-08-19 13:14:298402 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448403
8404 EXPECT_EQ(1, d.response_started_count());
8405 }
8406
8407 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8408 HttpNetworkSession::Params params;
8409 params.host_resolver = default_context_.host_resolver();
8410 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118411 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:448412 params.proxy_service = default_context_.proxy_service();
8413 params.ssl_config_service = default_context_.ssl_config_service();
8414 params.http_auth_handler_factory =
8415 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:418416 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:448417 params.http_server_properties = default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:448418
mmenkee65e7af2015-10-13 17:16:428419 HttpNetworkSession network_session(params);
[email protected]cba24642014-08-15 20:49:598420 scoped_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428421 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448422
8423 default_context_.set_http_transaction_factory(cache.get());
8424
8425 {
8426 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198427 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368428 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448429
[email protected]f7022f32014-08-21 16:32:198430 r->Start();
8431 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448432
[email protected]255620da2013-08-19 13:14:298433 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448434
8435 // The response will look like;
8436 // insert abc
8437 // insert xyz
8438 //
8439 // With a newline at the end which makes the split think that there are
8440 // three lines.
8441
8442 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008443 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448444 }
8445}
8446
davidben8ecc3072014-09-03 23:19:098447#if defined(OS_WIN)
8448
8449namespace {
8450
8451bool IsECDSACipherSuite(uint16_t cipher_suite) {
8452 const char* key_exchange;
8453 const char* cipher;
8454 const char* mac;
8455 bool is_aead;
8456 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
8457 return std::string(key_exchange).find("ECDSA") != std::string::npos;
8458}
8459
8460} // namespace
8461
8462// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
8463// verified.
davidben9399c952014-10-07 04:09:118464TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:098465 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
8466 LOG(INFO) << "Skipping test on this version.";
8467 return;
8468 }
8469
tommycli59a63432015-11-06 00:10:558470 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8471 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
davidben8ecc3072014-09-03 23:19:098472 ASSERT_TRUE(test_server.Start());
8473
8474 TestDelegate d;
8475 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558476 test_server.GetURL("/client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:098477 r->Start();
8478 EXPECT_TRUE(r->is_pending());
8479
8480 base::RunLoop().Run();
8481
8482 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298483 std::vector<std::string> lines = base::SplitString(
8484 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
davidben8ecc3072014-09-03 23:19:098485
8486 for (size_t i = 0; i < lines.size(); i++) {
8487 int cipher_suite;
8488 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
8489 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
8490 << "ClientHello advertised " << cipher_suite;
8491 }
8492}
8493
8494#endif // OS_WIN
8495
Adam Langley32352ad2014-10-14 22:31:008496class TestSSLConfigService : public SSLConfigService {
8497 public:
8498 TestSSLConfigService(bool ev_enabled,
8499 bool online_rev_checking,
8500 bool rev_checking_required_local_anchors)
8501 : ev_enabled_(ev_enabled),
8502 online_rev_checking_(online_rev_checking),
8503 rev_checking_required_local_anchors_(
8504 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:028505 min_version_(kDefaultSSLVersionMin),
8506 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
8507
avibf0746c2015-12-09 19:53:148508 void set_min_version(uint16_t version) { min_version_ = version; }
Adam Langley32352ad2014-10-14 22:31:008509
avibf0746c2015-12-09 19:53:148510 void set_fallback_min_version(uint16_t version) {
Adam Langley32352ad2014-10-14 22:31:008511 fallback_min_version_ = version;
8512 }
8513
8514 // SSLConfigService:
dchengb03027d2014-10-21 12:00:208515 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:008516 *config = SSLConfig();
8517 config->rev_checking_enabled = online_rev_checking_;
8518 config->verify_ev_cert = ev_enabled_;
8519 config->rev_checking_required_local_anchors =
8520 rev_checking_required_local_anchors_;
8521 if (fallback_min_version_) {
8522 config->version_fallback_min = fallback_min_version_;
8523 }
Adam Langleyac6f24b42014-10-31 20:24:028524 if (min_version_) {
8525 config->version_min = min_version_;
8526 }
Adam Langley32352ad2014-10-14 22:31:008527 }
8528
8529 protected:
dchengb03027d2014-10-21 12:00:208530 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:008531
8532 private:
8533 const bool ev_enabled_;
8534 const bool online_rev_checking_;
8535 const bool rev_checking_required_local_anchors_;
avibf0746c2015-12-09 19:53:148536 uint16_t min_version_;
8537 uint16_t fallback_min_version_;
Adam Langley32352ad2014-10-14 22:31:008538};
8539
8540class FallbackTestURLRequestContext : public TestURLRequestContext {
8541 public:
8542 explicit FallbackTestURLRequestContext(bool delay_initialization)
8543 : TestURLRequestContext(delay_initialization) {}
8544
avibf0746c2015-12-09 19:53:148545 void set_fallback_min_version(uint16_t version) {
Adam Langley32352ad2014-10-14 22:31:008546 TestSSLConfigService *ssl_config_service =
8547 new TestSSLConfigService(true /* check for EV */,
8548 false /* online revocation checking */,
8549 false /* require rev. checking for local
8550 anchors */);
8551 ssl_config_service->set_fallback_min_version(version);
8552 set_ssl_config_service(ssl_config_service);
8553 }
8554};
8555
[email protected]48d2b7c52014-06-27 01:16:558556class HTTPSFallbackTest : public testing::Test {
8557 public:
Adam Langley32352ad2014-10-14 22:31:008558 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298559 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558560
8561 protected:
8562 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8563 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008564 context_.Init();
8565 delegate_.set_allow_certificate_errors(true);
8566
[email protected]48d2b7c52014-06-27 01:16:558567 SpawnedTestServer test_server(
8568 SpawnedTestServer::TYPE_HTTPS,
8569 ssl_options,
8570 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8571 ASSERT_TRUE(test_server.Start());
8572
tommycli59a63432015-11-06 00:10:558573 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
8574 &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558575 request_->Start();
8576
8577 base::RunLoop().Run();
8578 }
8579
avibf0746c2015-12-09 19:53:148580 void set_fallback_min_version(uint16_t version) {
Adam Langley32352ad2014-10-14 22:31:008581 context_.set_fallback_min_version(version);
8582 }
8583
[email protected]48d2b7c52014-06-27 01:16:558584 void ExpectConnection(int version) {
8585 EXPECT_EQ(1, delegate_.response_started_count());
8586 EXPECT_NE(0, delegate_.bytes_received());
8587 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8588 request_->ssl_info().connection_status));
8589 EXPECT_TRUE(request_->ssl_info().connection_status &
8590 SSL_CONNECTION_VERSION_FALLBACK);
8591 }
8592
8593 void ExpectFailure(int error) {
8594 EXPECT_EQ(1, delegate_.response_started_count());
8595 EXPECT_FALSE(request_->status().is_success());
8596 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8597 EXPECT_EQ(error, request_->status().error());
8598 }
8599
8600 private:
8601 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008602 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558603 scoped_ptr<URLRequest> request_;
8604};
8605
davidbenb127ca82015-06-15 19:05:428606// Tests the TLS 1.0 fallback doesn't happen.
8607TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558608 SpawnedTestServer::SSLOptions ssl_options(
8609 SpawnedTestServer::SSLOptions::CERT_OK);
8610 ssl_options.tls_intolerant =
8611 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8612
8613 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428614 ExpectFailure(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION);
8615}
8616
8617// Tests the TLS 1.1 fallback.
8618TEST_F(HTTPSFallbackTest, TLSv1_1Fallback) {
davidbenb127ca82015-06-15 19:05:428619 SpawnedTestServer::SSLOptions ssl_options(
8620 SpawnedTestServer::SSLOptions::CERT_OK);
8621 ssl_options.tls_intolerant =
8622 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8623
8624 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8625 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
8626}
8627
8628// Tests that the TLS 1.1 fallback triggers on closed connections.
8629TEST_F(HTTPSFallbackTest, TLSv1_1FallbackClosed) {
davidbenb127ca82015-06-15 19:05:428630 SpawnedTestServer::SSLOptions ssl_options(
8631 SpawnedTestServer::SSLOptions::CERT_OK);
8632 ssl_options.tls_intolerant =
8633 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8634 ssl_options.tls_intolerance_type =
8635 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8636
8637 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8638 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558639}
8640
8641// This test is disabled on Android because the remote test server doesn't cause
8642// a TCP reset.
8643#if !defined(OS_ANDROID)
davidbenb127ca82015-06-15 19:05:428644// Tests fallback to TLS 1.1 on connection reset.
8645TEST_F(HTTPSFallbackTest, TLSv1_1FallbackReset) {
[email protected]48d2b7c52014-06-27 01:16:558646 SpawnedTestServer::SSLOptions ssl_options(
8647 SpawnedTestServer::SSLOptions::CERT_OK);
8648 ssl_options.tls_intolerant =
davidbenb127ca82015-06-15 19:05:428649 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
[email protected]48d2b7c52014-06-27 01:16:558650 ssl_options.tls_intolerance_type =
8651 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8652
8653 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428654 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558655}
8656#endif // !OS_ANDROID
8657
[email protected]12833302014-07-02 01:57:318658// Tests that we don't fallback on handshake failure with servers that implement
8659// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558660TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558661 SpawnedTestServer::SSLOptions ssl_options(
8662 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438663 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558664 // a version fallback.
8665 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438666 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558667 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8668 // connections are rejected.
8669 ssl_options.fallback_scsv_enabled = true;
8670
8671 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8672
8673 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8674 // intolerance. If the fallback SCSV is processed when the original error
8675 // that caused the fallback should be returned, which should be
8676 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8677 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8678}
8679
[email protected]12833302014-07-02 01:57:318680// Tests that we don't fallback on connection closed with servers that implement
8681// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318682TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318683 SpawnedTestServer::SSLOptions ssl_options(
8684 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438685 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318686 // a version fallback.
8687 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438688 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318689 ssl_options.tls_intolerance_type =
8690 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8691 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8692 // connections are rejected.
8693 ssl_options.fallback_scsv_enabled = true;
8694
8695 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8696
8697 // The original error should be replayed on rejected fallback.
8698 ExpectFailure(ERR_CONNECTION_CLOSED);
8699}
8700
davidbenb937d6c2015-05-14 04:53:428701// Test that fallback probe connections don't cause sessions to be cached.
8702TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008703 SpawnedTestServer::SSLOptions ssl_options(
8704 SpawnedTestServer::SSLOptions::CERT_OK);
8705 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428706 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008707 ssl_options.tls_intolerance_type =
8708 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8709 ssl_options.record_resume = true;
8710
8711 SpawnedTestServer test_server(
8712 SpawnedTestServer::TYPE_HTTPS,
8713 ssl_options,
8714 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8715 ASSERT_TRUE(test_server.Start());
8716
8717 SSLClientSocket::ClearSessionCache();
8718
davidbenb937d6c2015-05-14 04:53:428719 // Make a connection that does a probe fallback to TLSv1 but fails because
8720 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008721 // be inserted locally.
8722 {
8723 TestDelegate delegate;
8724 FallbackTestURLRequestContext context(true);
8725
davidbenb937d6c2015-05-14 04:53:428726 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008727 context.Init();
8728 scoped_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558729 test_server.GetURL("/"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008730 request->Start();
8731
8732 base::RunLoop().Run();
8733
8734 EXPECT_EQ(1, delegate.response_started_count());
8735 EXPECT_FALSE(request->status().is_success());
8736 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8737 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8738 request->status().error());
8739 }
8740
davidbenb937d6c2015-05-14 04:53:428741 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008742 {
8743 TestDelegate delegate;
8744 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428745 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008746
8747 context.Init();
davidben151423e2015-03-23 18:48:368748 scoped_ptr<URLRequest> request(context.CreateRequest(
8749 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008750 request->Start();
8751
8752 base::RunLoop().Run();
8753
8754 EXPECT_EQ(1, delegate.response_started_count());
8755 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428756 EXPECT_EQ(
8757 SSL_CONNECTION_VERSION_TLS1,
8758 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008759 EXPECT_TRUE(request->ssl_info().connection_status &
8760 SSL_CONNECTION_VERSION_FALLBACK);
8761
8762 std::vector<std::string> lines;
8763 // If no sessions were cached then the server should have seen two sessions
8764 // inserted with no lookups.
8765 AssertTwoDistinctSessionsInserted(delegate.data_received());
8766 }
8767}
8768
[email protected]a8fed1742013-12-27 02:14:248769class HTTPSSessionTest : public testing::Test {
8770 public:
8771 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598772 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248773
8774 default_context_.set_network_delegate(&default_network_delegate_);
8775 default_context_.set_cert_verifier(&cert_verifier_);
8776 default_context_.Init();
8777 }
dcheng67be2b1f2014-10-27 21:47:298778 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248779
8780 protected:
8781 MockCertVerifier cert_verifier_;
8782 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8783 TestURLRequestContext default_context_;
8784};
8785
8786// Tests that session resumption is not attempted if an invalid certificate
8787// is presented.
8788TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8789 SpawnedTestServer::SSLOptions ssl_options;
8790 ssl_options.record_resume = true;
8791 SpawnedTestServer test_server(
8792 SpawnedTestServer::TYPE_HTTPS,
8793 ssl_options,
8794 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8795 ASSERT_TRUE(test_server.Start());
8796
8797 SSLClientSocket::ClearSessionCache();
8798
8799 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598800 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248801 {
8802 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198803 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368804 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248805
[email protected]f7022f32014-08-21 16:32:198806 r->Start();
8807 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248808
8809 base::RunLoop().Run();
8810
8811 EXPECT_EQ(1, d.response_started_count());
8812 }
8813
8814 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8815 CloseAllConnections();
8816
8817 // Now change the certificate to be acceptable (so that the response is
8818 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598819 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248820 {
8821 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198822 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368823 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248824
[email protected]f7022f32014-08-21 16:32:198825 r->Start();
8826 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248827
8828 base::RunLoop().Run();
8829
8830 // The response will look like;
8831 // insert abc
8832 // insert xyz
8833 //
8834 // With a newline at the end which makes the split think that there are
8835 // three lines.
8836 //
8837 // If a session was presented (eg: a bug), then the response would look
8838 // like;
8839 // insert abc
8840 // lookup abc
8841 // insert xyz
8842
8843 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008844 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248845 }
8846}
8847
[email protected]dffe8242012-03-20 15:14:278848// This the fingerprint of the "Testing CA" certificate used by the testserver.
8849// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268850static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278851 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8852 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8853
[email protected]51523f52013-07-31 21:57:288854// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8855// testserver.
8856static const SHA256HashValue kOCSPTestCertSPKI = { {
8857 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8858 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8859 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8860 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8861} };
8862
[email protected]dffe8242012-03-20 15:14:278863// This is the policy OID contained in the certificates that testserver
8864// generates.
8865static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8866
8867class HTTPSOCSPTest : public HTTPSRequestTest {
8868 public:
8869 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098870 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088871 ev_test_policy_(
8872 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8873 kOCSPTestCertFingerprint,
8874 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028875 }
8876
dcheng67be2b1f2014-10-27 21:47:298877 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098878 SetupContext(&context_);
8879 context_.Init();
[email protected]dffe8242012-03-20 15:14:278880
[email protected]cba24642014-08-15 20:49:598881 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208882 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428883 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508884 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278885
davidben71f35ff2015-04-17 20:54:488886#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098887 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278888 EnsureNSSHttpIOInit();
8889#endif
8890 }
8891
[email protected]ce7d0cbc2013-05-03 18:57:228892 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278893 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538894 // We always overwrite out_cert_status.
8895 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228896 SpawnedTestServer test_server(
8897 SpawnedTestServer::TYPE_HTTPS,
8898 ssl_options,
8899 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278900 ASSERT_TRUE(test_server.Start());
8901
8902 TestDelegate d;
8903 d.set_allow_certificate_errors(true);
tommycli59a63432015-11-06 00:10:558904 scoped_ptr<URLRequest> r(
8905 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198906 r->Start();
[email protected]dffe8242012-03-20 15:14:278907
[email protected]255620da2013-08-19 13:14:298908 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278909
8910 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198911 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278912 }
8913
dcheng67be2b1f2014-10-27 21:47:298914 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488915#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278916 ShutdownNSSHttpIO();
8917#endif
8918 }
8919
[email protected]a13234c2012-03-20 21:45:028920 protected:
8921 // SetupContext configures the URLRequestContext that will be used for making
8922 // connetions to testserver. This can be overridden in test subclasses for
8923 // different behaviour.
8924 virtual void SetupContext(URLRequestContext* context) {
8925 context->set_ssl_config_service(
8926 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208927 true /* online revocation checking */,
8928 false /* require rev. checking for local
8929 anchors */));
[email protected]a13234c2012-03-20 21:45:028930 }
8931
[email protected]dffe8242012-03-20 15:14:278932 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098933 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088934 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278935};
8936
[email protected]a13234c2012-03-20 21:45:028937static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018938#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028939 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8940 // have that ability on other platforms.
8941 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8942#else
8943 return 0;
8944#endif
8945}
8946
[email protected]3a86a712013-07-30 07:16:208947// SystemSupportsHardFailRevocationChecking returns true iff the current
8948// operating system supports revocation checking and can distinguish between
8949// situations where a given certificate lacks any revocation information (eg:
8950// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8951// revocation information cannot be obtained (eg: the CRL was unreachable).
8952// If it does not, then tests which rely on 'hard fail' behaviour should be
8953// skipped.
8954static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:488955#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:208956 return true;
8957#else
8958 return false;
8959#endif
8960}
8961
[email protected]a13234c2012-03-20 21:45:028962// SystemUsesChromiumEVMetadata returns true iff the current operating system
8963// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8964// several tests are effected because our testing EV certificate won't be
8965// recognised as EV.
8966static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328967#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578968 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8969 return false;
[email protected]e1b2d732014-03-28 16:20:328970#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8971 // On OS X and Android, we use the system to tell us whether a certificate is
8972 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018973 return false;
8974#else
8975 return true;
8976#endif
8977}
8978
[email protected]b6f2de32012-08-17 04:35:088979static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008980#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578981 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8982 return false;
8983#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028984 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8985#elif defined(OS_ANDROID)
8986 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8987 return false;
8988#else
8989 return true;
8990#endif
8991}
8992
davidbend1fb2f12014-11-08 02:51:008993static bool SystemSupportsOCSPStapling() {
mathpc992e602015-10-21 20:34:038994#if defined(USE_NSS_CERTS) || defined(OS_IOS)
8995 return true;
8996#elif defined(OS_WIN)
8997 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8998#else
8999 return false;
9000#endif
davidbend1fb2f12014-11-08 02:51:009001}
9002
[email protected]dffe8242012-03-20 15:14:279003TEST_F(HTTPSOCSPTest, Valid) {
9004 if (!SystemSupportsOCSP()) {
9005 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9006 return;
9007 }
9008
[email protected]ce7d0cbc2013-05-03 18:57:229009 SpawnedTestServer::SSLOptions ssl_options(
9010 SpawnedTestServer::SSLOptions::CERT_AUTO);
9011 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:279012
[email protected]924e9f92012-12-16 22:00:539013 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129014 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279015
9016 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9017
[email protected]a13234c2012-03-20 21:45:029018 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9019 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:279020
9021 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9022}
9023
9024TEST_F(HTTPSOCSPTest, Revoked) {
9025 if (!SystemSupportsOCSP()) {
9026 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9027 return;
9028 }
9029
[email protected]ce7d0cbc2013-05-03 18:57:229030 SpawnedTestServer::SSLOptions ssl_options(
9031 SpawnedTestServer::SSLOptions::CERT_AUTO);
9032 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:279033
9034 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129035 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279036
[email protected]a592c0432012-12-01 18:10:299037#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:279038 // Doesn't pass on OS X yet for reasons that need to be investigated.
9039 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9040#endif
9041 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9042 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9043}
9044
9045TEST_F(HTTPSOCSPTest, Invalid) {
9046 if (!SystemSupportsOCSP()) {
9047 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9048 return;
9049 }
9050
[email protected]ce7d0cbc2013-05-03 18:57:229051 SpawnedTestServer::SSLOptions ssl_options(
9052 SpawnedTestServer::SSLOptions::CERT_AUTO);
9053 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:279054
[email protected]924e9f92012-12-16 22:00:539055 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129056 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279057
[email protected]a13234c2012-03-20 21:45:029058 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:279059 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279060
9061 // Without a positive OCSP response, we shouldn't show the EV status.
9062 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9063 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9064}
[email protected]a13234c2012-03-20 21:45:029065
davidbend1fb2f12014-11-08 02:51:009066TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:039067 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009068 LOG(WARNING)
9069 << "Skipping test because system doesn't support OCSP stapling";
9070 return;
9071 }
9072
9073 SpawnedTestServer::SSLOptions ssl_options(
9074 SpawnedTestServer::SSLOptions::CERT_AUTO);
9075 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9076 ssl_options.staple_ocsp_response = true;
9077 ssl_options.ocsp_server_unavailable = true;
9078
9079 CertStatus cert_status;
9080 DoConnection(ssl_options, &cert_status);
9081
9082 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9083
9084 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9085 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9086
9087 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9088}
9089
davidben6c3191b2014-11-21 22:38:049090// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489091#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049092#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9093#else
9094#define MAYBE_RevokedStapled RevokedStapled
9095#endif
9096TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:039097 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009098 LOG(WARNING)
9099 << "Skipping test because system doesn't support OCSP stapling";
9100 return;
9101 }
9102
9103 SpawnedTestServer::SSLOptions ssl_options(
9104 SpawnedTestServer::SSLOptions::CERT_AUTO);
9105 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9106 ssl_options.staple_ocsp_response = true;
9107 ssl_options.ocsp_server_unavailable = true;
9108
9109 CertStatus cert_status;
9110 DoConnection(ssl_options, &cert_status);
9111
9112 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9113 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9114 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9115}
9116
[email protected]3a86a712013-07-30 07:16:209117class HTTPSHardFailTest : public HTTPSOCSPTest {
9118 protected:
dchengb03027d2014-10-21 12:00:209119 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:209120 context->set_ssl_config_service(
9121 new TestSSLConfigService(false /* check for EV */,
9122 false /* online revocation checking */,
9123 true /* require rev. checking for local
9124 anchors */));
9125 }
9126};
9127
[email protected]3a86a712013-07-30 07:16:209128TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
9129 if (!SystemSupportsOCSP()) {
9130 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9131 return;
9132 }
9133
9134 if (!SystemSupportsHardFailRevocationChecking()) {
9135 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
9136 << "revocation checking";
9137 return;
9138 }
9139
9140 SpawnedTestServer::SSLOptions ssl_options(
9141 SpawnedTestServer::SSLOptions::CERT_AUTO);
9142 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9143
9144 CertStatus cert_status;
9145 DoConnection(ssl_options, &cert_status);
9146
9147 EXPECT_EQ(CERT_STATUS_REVOKED,
9148 cert_status & CERT_STATUS_REVOKED);
9149
9150 // Without a positive OCSP response, we shouldn't show the EV status.
9151 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9152}
9153
[email protected]a13234c2012-03-20 21:45:029154class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
9155 protected:
dchengb03027d2014-10-21 12:00:209156 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:029157 context->set_ssl_config_service(
9158 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:209159 false /* online revocation checking */,
9160 false /* require rev. checking for local
9161 anchors */));
[email protected]a13234c2012-03-20 21:45:029162 }
9163};
9164
9165TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
9166 if (!SystemSupportsOCSP()) {
9167 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9168 return;
9169 }
9170
[email protected]ce7d0cbc2013-05-03 18:57:229171 SpawnedTestServer::SSLOptions ssl_options(
9172 SpawnedTestServer::SSLOptions::CERT_AUTO);
9173 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029174 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9175
[email protected]924e9f92012-12-16 22:00:539176 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129177 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029178
9179 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9180 cert_status & CERT_STATUS_ALL_ERRORS);
9181
9182 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089183 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9184 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029185}
9186
[email protected]be0fff62013-08-29 23:37:489187TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
9188 if (!SystemSupportsOCSP()) {
9189 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9190 return;
9191 }
9192
9193 SpawnedTestServer::SSLOptions ssl_options(
9194 SpawnedTestServer::SSLOptions::CERT_AUTO);
9195 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9196 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9197
9198 CertStatus cert_status;
9199 DoConnection(ssl_options, &cert_status);
9200
9201 // Currently only works for Windows. When using NSS or OS X, it's not
9202 // possible to determine whether the check failed because of actual
9203 // revocation or because there was an OCSP failure.
9204#if defined(OS_WIN)
9205 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9206#else
9207 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9208#endif
9209
9210 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9211 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9212 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9213}
9214
[email protected]a13234c2012-03-20 21:45:029215TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
9216 if (!SystemSupportsOCSP()) {
9217 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9218 return;
9219 }
9220
[email protected]ce7d0cbc2013-05-03 18:57:229221 SpawnedTestServer::SSLOptions ssl_options(
9222 SpawnedTestServer::SSLOptions::CERT_AUTO);
9223 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:029224 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9225
9226 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129227 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029228
9229 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9230
9231 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9232 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:089233 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9234 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029235}
9236
9237TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
9238 if (!SystemSupportsOCSP()) {
9239 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9240 return;
9241 }
9242
[email protected]ce7d0cbc2013-05-03 18:57:229243 SpawnedTestServer::SSLOptions ssl_options(
9244 SpawnedTestServer::SSLOptions::CERT_AUTO);
9245 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029246 SSLConfigService::SetCRLSet(
9247 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9248
9249 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129250 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029251
9252 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9253 cert_status & CERT_STATUS_ALL_ERRORS);
9254
9255 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089256 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9257 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029258}
9259
[email protected]51523f52013-07-31 21:57:289260TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9261 if (!SystemSupportsOCSP()) {
9262 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9263 return;
9264 }
9265
9266 SpawnedTestServer::SSLOptions ssl_options(
9267 SpawnedTestServer::SSLOptions::CERT_AUTO);
9268 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9269 SSLConfigService::SetCRLSet(
9270 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9271 false, &kOCSPTestCertSPKI, "")));
9272
9273 CertStatus cert_status;
9274 DoConnection(ssl_options, &cert_status);
9275
9276 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9277 // revocation check for EV.
9278 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9279 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9280 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9281 EXPECT_FALSE(
9282 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9283}
9284
9285TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9286 if (!SystemSupportsOCSP()) {
9287 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9288 return;
9289 }
9290
[email protected]ce7d0cbc2013-05-03 18:57:229291 SpawnedTestServer::SSLOptions ssl_options(
9292 SpawnedTestServer::SSLOptions::CERT_AUTO);
9293 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029294 SSLConfigService::SetCRLSet(
9295 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9296
[email protected]51523f52013-07-31 21:57:289297 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129298 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029299
[email protected]51523f52013-07-31 21:57:289300 // Even with a fresh CRLSet, we should still do online revocation checks when
9301 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9302 // test.
9303 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9304 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029305
[email protected]51523f52013-07-31 21:57:289306 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029307 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289308 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029309}
9310
[email protected]b6f2de32012-08-17 04:35:089311TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9312 // Test that when EV verification is requested, but online revocation
9313 // checking is disabled, and the leaf certificate is not in fact EV, that
9314 // no revocation checking actually happens.
9315 if (!SystemSupportsOCSP()) {
9316 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9317 return;
9318 }
9319
9320 // Unmark the certificate's OID as EV, which should disable revocation
9321 // checking (as per the user preference)
9322 ev_test_policy_.reset();
9323
[email protected]ce7d0cbc2013-05-03 18:57:229324 SpawnedTestServer::SSLOptions ssl_options(
9325 SpawnedTestServer::SSLOptions::CERT_AUTO);
9326 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089327 SSLConfigService::SetCRLSet(
9328 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9329
9330 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129331 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:089332
9333 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9334
9335 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9336 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9337}
9338
[email protected]a13234c2012-03-20 21:45:029339class HTTPSCRLSetTest : public HTTPSOCSPTest {
9340 protected:
dchengb03027d2014-10-21 12:00:209341 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:029342 context->set_ssl_config_service(
9343 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:209344 false /* online revocation checking */,
9345 false /* require rev. checking for local
9346 anchors */));
[email protected]a13234c2012-03-20 21:45:029347 }
9348};
9349
9350TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229351 SpawnedTestServer::SSLOptions ssl_options(
9352 SpawnedTestServer::SSLOptions::CERT_AUTO);
9353 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029354 SSLConfigService::SetCRLSet(
9355 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9356
[email protected]924e9f92012-12-16 22:00:539357 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129358 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029359
9360 // If we're not trying EV verification then, even if the CRLSet has expired,
9361 // we don't fall back to online revocation checks.
9362 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9363 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9364 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9365}
[email protected]51523f52013-07-31 21:57:289366
9367TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309368#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289369 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9370 return;
9371#endif
9372
9373 SpawnedTestServer::SSLOptions ssl_options(
9374 SpawnedTestServer::SSLOptions::CERT_AUTO);
9375 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9376 ssl_options.cert_serial = 10;
9377 SSLConfigService::SetCRLSet(
9378 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9379 false, &kOCSPTestCertSPKI, "\x0a")));
9380
9381 CertStatus cert_status = 0;
9382 DoConnection(ssl_options, &cert_status);
9383
9384 // If the certificate is recorded as revoked in the CRLSet, that should be
9385 // reflected without online revocation checking.
9386 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9387 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9388 EXPECT_FALSE(
9389 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9390}
[email protected]316c1e5e2012-09-12 15:17:449391#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279392
mmenke9f2ec60c2015-06-01 20:59:479393#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9394// These tests aren't passing on Android. Either the RemoteTestServer isn't
9395// starting up successfully, or it can't access the test files.
9396// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319397class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119398 public:
[email protected]d9fca99a2012-02-24 16:16:209399 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:479400 : ftp_transaction_factory_(&host_resolver_),
tommycli59a63432015-11-06 00:10:559401 ftp_test_server_(SpawnedTestServer::TYPE_FTP,
9402 SpawnedTestServer::kLocalhost,
9403 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:479404 // Can't use |default_context_|'s HostResolver to set up the
9405 // FTPTransactionFactory because it hasn't been created yet.
9406 default_context_.set_host_resolver(&host_resolver_);
9407 }
9408
9409 // URLRequestTest interface:
9410 void SetUpFactory() override {
9411 // Add FTP support to the default URLRequestContext.
9412 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:209413 "ftp",
9414 make_scoped_ptr(new FtpProtocolHandler(&ftp_transaction_factory_)));
mmenke9f2ec60c2015-06-01 20:59:479415 }
9416
9417 std::string GetTestFileContents() {
9418 base::FilePath path;
9419 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9420 path = path.Append(kTestFilePath);
9421 path = path.AppendASCII(kFtpTestFile);
9422 std::string contents;
9423 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9424 return contents;
[email protected]95409e12010-08-17 20:07:119425 }
9426
[email protected]b89ca032009-08-31 21:41:319427 protected:
mmenke9f2ec60c2015-06-01 20:59:479428 MockHostResolver host_resolver_;
9429 FtpNetworkLayer ftp_transaction_factory_;
9430
tommycli59a63432015-11-06 00:10:559431 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:319432};
9433
[email protected]d2a133182012-08-05 16:44:089434// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099435TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089436 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089437
9438 TestDelegate d;
9439 {
davidben151423e2015-03-23 18:48:369440 scoped_ptr<URLRequest> r(
9441 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199442 r->Start();
9443 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089444
[email protected]255620da2013-08-19 13:14:299445 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089446
[email protected]f7022f32014-08-21 16:32:199447 EXPECT_FALSE(r->is_pending());
9448 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
9449 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:089450 }
9451}
9452
mmenke9f2ec60c2015-06-01 20:59:479453TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:559454 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119455
[email protected]a25e90e2009-09-09 17:05:379456 TestDelegate d;
9457 {
[email protected]f7022f32014-08-21 16:32:199458 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559459 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199460 r->Start();
9461 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379462
[email protected]255620da2013-08-19 13:14:299463 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379464
[email protected]f7022f32014-08-21 16:32:199465 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379466 EXPECT_EQ(1, d.response_started_count());
9467 EXPECT_FALSE(d.received_data_before_response());
9468 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:559469 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199470 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559471 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199472 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379473 }
9474}
9475
mmenke9f2ec60c2015-06-01 20:59:479476TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:559477 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119478
[email protected]dd265012009-01-08 20:45:279479 TestDelegate d;
9480 {
[email protected]f7022f32014-08-21 16:32:199481 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559482 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199483 r->Start();
9484 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279485
[email protected]255620da2013-08-19 13:14:299486 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279487
[email protected]f7022f32014-08-21 16:32:199488 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279489 EXPECT_EQ(1, d.response_started_count());
9490 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479491 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559492 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199493 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559494 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199495 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279496 }
9497}
9498
mmenke9f2ec60c2015-06-01 20:59:479499TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:559500 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119501
[email protected]dd265012009-01-08 20:45:279502 TestDelegate d;
9503 {
tommycli59a63432015-11-06 00:10:559504 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9505 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9506 "chrome"),
9507 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199508 r->Start();
9509 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279510
[email protected]255620da2013-08-19 13:14:299511 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279512
[email protected]f7022f32014-08-21 16:32:199513 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479514 EXPECT_EQ(1, d.response_started_count());
9515 EXPECT_FALSE(d.received_data_before_response());
9516 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559517 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199518 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559519 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199520 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:259521
9522 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:199523 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:259524 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:279525 }
9526}
9527
mmenke9f2ec60c2015-06-01 20:59:479528TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:559529 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119530
[email protected]dd265012009-01-08 20:45:279531 TestDelegate d;
9532 {
[email protected]f7022f32014-08-21 16:32:199533 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559534 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9535 "wrong_password"),
davidben151423e2015-03-23 18:48:369536 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199537 r->Start();
9538 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279539
[email protected]255620da2013-08-19 13:14:299540 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279541
[email protected]f7022f32014-08-21 16:32:199542 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279543 EXPECT_EQ(1, d.response_started_count());
9544 EXPECT_FALSE(d.received_data_before_response());
9545 EXPECT_EQ(d.bytes_received(), 0);
9546 }
9547}
9548
mmenke9f2ec60c2015-06-01 20:59:479549TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:559550 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119551
[email protected]8b8a197d2009-08-26 15:57:589552 TestDelegate d;
9553 // Set correct login credentials. The delegate will be asked for them when
9554 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589555 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589556 {
[email protected]f7022f32014-08-21 16:32:199557 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559558 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9559 "wrong_password"),
davidben151423e2015-03-23 18:48:369560 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199561 r->Start();
9562 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589563
[email protected]255620da2013-08-19 13:14:299564 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589565
[email protected]f7022f32014-08-21 16:32:199566 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589567 EXPECT_EQ(1, d.response_started_count());
9568 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479569 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589570 }
9571}
9572
mmenke9f2ec60c2015-06-01 20:59:479573TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:559574 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119575
[email protected]dd265012009-01-08 20:45:279576 TestDelegate d;
9577 {
mmenke9f2ec60c2015-06-01 20:59:479578 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559579 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9580 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479581 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199582 r->Start();
9583 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279584
[email protected]255620da2013-08-19 13:14:299585 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279586
[email protected]f7022f32014-08-21 16:32:199587 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279588 EXPECT_EQ(1, d.response_started_count());
9589 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479590 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279591 }
9592}
[email protected]8b8a197d2009-08-26 15:57:589593
mmenke9f2ec60c2015-06-01 20:59:479594TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:559595 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119596
[email protected]8b8a197d2009-08-26 15:57:589597 TestDelegate d;
9598 // Set correct login credentials. The delegate will be asked for them when
9599 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589600 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589601 {
mmenke9f2ec60c2015-06-01 20:59:479602 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559603 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9604 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479605 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199606 r->Start();
9607 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589608
[email protected]255620da2013-08-19 13:14:299609 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589610
[email protected]f7022f32014-08-21 16:32:199611 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589612 EXPECT_EQ(1, d.response_started_count());
9613 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479614 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589615 }
9616}
[email protected]60a3df52009-09-22 16:13:249617
mmenke9f2ec60c2015-06-01 20:59:479618TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:559619 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119620
[email protected]60a3df52009-09-22 16:13:249621 scoped_ptr<TestDelegate> d(new TestDelegate);
9622 {
9623 // Pass correct login identity in the URL.
tommycli59a63432015-11-06 00:10:559624 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9625 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9626 "chrome"),
9627 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199628 r->Start();
9629 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249630
[email protected]255620da2013-08-19 13:14:299631 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249632
[email protected]f7022f32014-08-21 16:32:199633 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249634 EXPECT_EQ(1, d->response_started_count());
9635 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479636 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249637 }
9638
9639 d.reset(new TestDelegate);
9640 {
9641 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199642 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559643 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199644 r->Start();
9645 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249646
[email protected]255620da2013-08-19 13:14:299647 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249648
[email protected]f7022f32014-08-21 16:32:199649 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249650 EXPECT_EQ(1, d->response_started_count());
9651 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479652 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249653 }
9654}
9655
mmenke9f2ec60c2015-06-01 20:59:479656TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:559657 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119658
[email protected]60a3df52009-09-22 16:13:249659 scoped_ptr<TestDelegate> d(new TestDelegate);
9660 // Set correct login credentials. The delegate will be asked for them when
9661 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589662 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249663 {
[email protected]f7022f32014-08-21 16:32:199664 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559665 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9666 "wrong_password"),
davidben151423e2015-03-23 18:48:369667 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199668 r->Start();
9669 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249670
[email protected]255620da2013-08-19 13:14:299671 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249672
[email protected]f7022f32014-08-21 16:32:199673 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249674 EXPECT_EQ(1, d->response_started_count());
9675 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479676 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249677 }
9678
9679 // Use a new delegate without explicit credentials. The cached ones should be
9680 // used.
9681 d.reset(new TestDelegate);
9682 {
9683 // Don't pass wrong credentials in the URL, they would override valid cached
9684 // ones.
[email protected]f7022f32014-08-21 16:32:199685 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559686 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199687 r->Start();
9688 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249689
[email protected]255620da2013-08-19 13:14:299690 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249691
[email protected]f7022f32014-08-21 16:32:199692 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249693 EXPECT_EQ(1, d->response_started_count());
9694 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479695 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249696 }
9697}
[email protected]316c1e5e2012-09-12 15:17:449698#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519699
ttuttlec0c828492015-05-15 01:25:559700TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9701 TestDelegate d;
9702 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9703 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9704 d.set_quit_on_network_start(true);
9705
9706 EXPECT_FALSE(req->response_info().network_accessed);
9707
9708 req->Start();
9709 base::RunLoop().Run();
9710
9711 EXPECT_EQ(1, d.received_before_network_start_count());
9712 EXPECT_EQ(0, d.response_started_count());
9713 EXPECT_FALSE(req->response_info().network_accessed);
9714
9715 req->ResumeNetworkStart();
9716 base::RunLoop().Run();
9717}
9718
9719TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9720 TestDelegate d;
9721 scoped_ptr<URLRequest> req(
9722 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9723
9724 EXPECT_FALSE(req->response_info().network_accessed);
9725
9726 req->Start();
9727 base::RunLoop().Run();
9728
9729 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9730 EXPECT_FALSE(req->response_info().network_accessed);
9731}
9732
9733TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9734 MockHostResolver host_resolver;
9735 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9736 TestURLRequestContext context(true);
9737 context.set_network_delegate(&network_delegate);
9738 context.set_host_resolver(&host_resolver);
9739 host_resolver.rules()->AddSimulatedFailure("*");
9740 context.Init();
9741
9742 TestDelegate d;
9743 scoped_ptr<URLRequest> req(context.CreateRequest(
9744 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9745
9746 EXPECT_FALSE(req->response_info().network_accessed);
9747
9748 req->Start();
9749 base::RunLoop().Run();
9750 EXPECT_TRUE(req->response_info().network_accessed);
9751}
9752
mmenkeed0498b2015-12-08 23:20:429753// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:229754// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:429755TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:229756 TestDelegate d;
9757 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9758 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
9759
mmenkeed0498b2015-12-08 23:20:429760 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:229761 req.get(), &default_network_delegate_,
9762 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:429763 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
9764 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:229765
9766 req->Start();
9767 req->Cancel();
alexanderkcd904b52015-07-24 18:57:229768 base::RunLoop().RunUntilIdle();
9769 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
9770 EXPECT_EQ(0, d.received_redirect_count());
9771}
9772
[email protected]7461a402011-03-24 23:19:519773} // namespace net