blob: b9e1ecac6da4bac5aacad0d675f43805479c5006 [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
2098// Check that a failure to connect to the proxy is reported to the network
2099// delegate.
2100TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2101 MockHostResolver host_resolver;
2102 host_resolver.rules()->AddSimulatedFailure("*");
2103
[email protected]ceefd7fd2012-11-29 00:36:242104 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442105 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2106
2107 TestDelegate d;
davidben151423e2015-03-23 18:48:362108 scoped_ptr<URLRequest> req(
2109 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192110 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442111
[email protected]f7022f32014-08-21 16:32:192112 req->Start();
[email protected]255620da2013-08-19 13:14:292113 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442114
2115 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192116 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152117 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192118 EXPECT_TRUE(req->proxy_server().IsEmpty());
2119 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2120 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442121
2122 EXPECT_EQ(1, network_delegate.error_count());
2123 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2124 EXPECT_EQ(1, network_delegate.completed_requests());
2125}
2126
[email protected]cba24642014-08-15 20:49:592127// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442128// content is empty.
2129TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2130 TestDelegate d;
davidben151423e2015-03-23 18:48:362131 scoped_ptr<URLRequest> req(
2132 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192133 req->Start();
[email protected]255620da2013-08-19 13:14:292134 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442135 EXPECT_EQ("", d.data_received());
2136 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2137}
2138
[email protected]5033ab82013-03-22 20:17:462139// Make sure that SetPriority actually sets the URLRequest's priority
2140// correctly, both before and after start.
2141TEST_F(URLRequestTest, SetPriorityBasic) {
2142 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192143 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362144 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192145 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462146
[email protected]f7022f32014-08-21 16:32:192147 req->SetPriority(LOW);
2148 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462149
[email protected]f7022f32014-08-21 16:32:192150 req->Start();
2151 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462152
[email protected]f7022f32014-08-21 16:32:192153 req->SetPriority(MEDIUM);
2154 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462155}
2156
2157// Make sure that URLRequest calls SetPriority on a job before calling
2158// Start on it.
2159TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2160 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192161 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362162 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192163 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462164
mmenkeed0498b2015-12-08 23:20:422165 RequestPriority job_priority;
2166 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
2167 req.get(), &default_network_delegate_, &job_priority));
2168 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2169 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462170
[email protected]f7022f32014-08-21 16:32:192171 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462172
[email protected]f7022f32014-08-21 16:32:192173 req->Start();
mmenkeed0498b2015-12-08 23:20:422174 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462175}
2176
2177// Make sure that URLRequest passes on its priority updates to its
2178// job.
2179TEST_F(URLRequestTest, SetJobPriority) {
2180 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192181 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362182 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462183
mmenkeed0498b2015-12-08 23:20:422184 RequestPriority job_priority;
2185 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
2186 req.get(), &default_network_delegate_, &job_priority));
2187 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462188
[email protected]f7022f32014-08-21 16:32:192189 req->SetPriority(LOW);
2190 req->Start();
mmenkeed0498b2015-12-08 23:20:422191 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462192
[email protected]f7022f32014-08-21 16:32:192193 req->SetPriority(MEDIUM);
2194 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422195 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462196}
2197
[email protected]bb1c4662013-11-14 00:00:072198// Setting the IGNORE_LIMITS load flag should be okay if the priority
2199// is MAXIMUM_PRIORITY.
2200TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2201 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192202 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362203 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192204 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072205
mmenkeed0498b2015-12-08 23:20:422206 RequestPriority job_priority;
2207 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
2208 req.get(), &default_network_delegate_, &job_priority));
2209 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072210
[email protected]f7022f32014-08-21 16:32:192211 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2212 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072213
[email protected]f7022f32014-08-21 16:32:192214 req->SetPriority(MAXIMUM_PRIORITY);
2215 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072216
[email protected]f7022f32014-08-21 16:32:192217 req->Start();
2218 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422219 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072220}
2221
nick5d570de92015-05-04 20:16:162222namespace {
2223
2224// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552225class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442226 public:
tommycli59a63432015-11-06 00:10:552227 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2228 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272229 }
tommycli59a63432015-11-06 00:10:552230
2231 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2232};
tommyclieae5f75f2015-11-05 19:07:272233
nick5d570de92015-05-04 20:16:162234} // namespace
2235
[email protected]f2f31b32013-01-16 23:24:092236TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442237 LocalHttpTestServer test_server;
2238 ASSERT_TRUE(test_server.Start());
2239
2240 TestURLRequestContext context;
2241 scoped_refptr<DelayedCookieMonster> delayed_cm =
2242 new DelayedCookieMonster();
2243 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502244 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442245
2246 // Set up a cookie.
2247 {
2248 TestNetworkDelegate network_delegate;
2249 context.set_network_delegate(&network_delegate);
2250 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192251 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552252 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362253 &d));
[email protected]f7022f32014-08-21 16:32:192254 req->Start();
[email protected]255620da2013-08-19 13:14:292255 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442256 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2257 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2258 EXPECT_EQ(1, network_delegate.set_cookie_count());
2259 }
2260
2261 // Verify that the cookie is set.
2262 {
2263 TestNetworkDelegate network_delegate;
2264 context.set_network_delegate(&network_delegate);
2265 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192266 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552267 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192268 req->Start();
[email protected]255620da2013-08-19 13:14:292269 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442270
2271 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2272 != std::string::npos);
2273 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2274 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2275 }
2276}
2277
[email protected]f2f31b32013-01-16 23:24:092278TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442279 LocalHttpTestServer test_server;
2280 ASSERT_TRUE(test_server.Start());
2281
2282 // Set up a cookie.
2283 {
2284 TestNetworkDelegate network_delegate;
2285 default_context_.set_network_delegate(&network_delegate);
2286 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192287 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552288 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362289 &d));
[email protected]f7022f32014-08-21 16:32:192290 req->Start();
[email protected]255620da2013-08-19 13:14:292291 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442292 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2293 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2294 }
2295
2296 // Verify that the cookie is set.
2297 {
2298 TestNetworkDelegate network_delegate;
2299 default_context_.set_network_delegate(&network_delegate);
2300 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192301 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552302 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192303 req->Start();
[email protected]255620da2013-08-19 13:14:292304 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442305
2306 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2307 != std::string::npos);
2308 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2309 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2310 }
2311
2312 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2313 {
2314 TestNetworkDelegate network_delegate;
2315 default_context_.set_network_delegate(&network_delegate);
2316 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192317 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552318 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192319 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2320 req->Start();
[email protected]255620da2013-08-19 13:14:292321 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442322
2323 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2324 == std::string::npos);
2325
2326 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2327 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2328 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2329 }
2330}
2331
2332TEST_F(URLRequestTest, DoNotSaveCookies) {
2333 LocalHttpTestServer test_server;
2334 ASSERT_TRUE(test_server.Start());
2335
2336 // Set up a cookie.
2337 {
2338 TestNetworkDelegate network_delegate;
2339 default_context_.set_network_delegate(&network_delegate);
2340 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192341 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552342 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362343 &d));
[email protected]f7022f32014-08-21 16:32:192344 req->Start();
[email protected]255620da2013-08-19 13:14:292345 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442346
2347 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2348 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2349 EXPECT_EQ(1, network_delegate.set_cookie_count());
2350 }
2351
2352 // Try to set-up another cookie and update the previous cookie.
2353 {
2354 TestNetworkDelegate network_delegate;
2355 default_context_.set_network_delegate(&network_delegate);
2356 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192357 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552358 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362359 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192360 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2361 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442362
[email protected]255620da2013-08-19 13:14:292363 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442364
2365 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2366 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2367 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2368 EXPECT_EQ(0, network_delegate.set_cookie_count());
2369 }
2370
2371 // Verify the cookies weren't saved or updated.
2372 {
2373 TestNetworkDelegate network_delegate;
2374 default_context_.set_network_delegate(&network_delegate);
2375 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192376 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552377 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192378 req->Start();
[email protected]255620da2013-08-19 13:14:292379 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442380
2381 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2382 == std::string::npos);
2383 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2384 != std::string::npos);
2385
2386 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2387 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2388 EXPECT_EQ(0, network_delegate.set_cookie_count());
2389 }
2390}
2391
2392TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2393 LocalHttpTestServer test_server;
2394 ASSERT_TRUE(test_server.Start());
2395
2396 // Set up a cookie.
2397 {
2398 TestNetworkDelegate network_delegate;
2399 default_context_.set_network_delegate(&network_delegate);
2400 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192401 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552402 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362403 &d));
[email protected]f7022f32014-08-21 16:32:192404 req->Start();
[email protected]255620da2013-08-19 13:14:292405 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442406
2407 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2408 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2409 }
2410
2411 // Verify that the cookie is set.
2412 {
2413 TestNetworkDelegate network_delegate;
2414 default_context_.set_network_delegate(&network_delegate);
2415 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192416 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552417 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192418 req->Start();
[email protected]255620da2013-08-19 13:14:292419 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442420
2421 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2422 != std::string::npos);
2423
2424 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2425 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2426 }
2427
2428 // Verify that the cookie isn't sent.
2429 {
2430 TestNetworkDelegate network_delegate;
2431 default_context_.set_network_delegate(&network_delegate);
2432 TestDelegate d;
2433 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192434 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552435 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192436 req->Start();
[email protected]255620da2013-08-19 13:14:292437 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442438
2439 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2440 == std::string::npos);
2441
[email protected]22e045f2013-09-20 03:54:032442 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442443 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2444 }
2445}
2446
marqf14fff8d2015-12-02 15:52:292447// TODO(crbug.com/564656) This test is flaky on iOS.
2448#if defined(OS_IOS)
2449#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2450#else
2451#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2452#endif
[email protected]316c1e5e2012-09-12 15:17:442453TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2454 LocalHttpTestServer test_server;
2455 ASSERT_TRUE(test_server.Start());
2456
2457 // Set up a cookie.
2458 {
2459 TestNetworkDelegate network_delegate;
2460 default_context_.set_network_delegate(&network_delegate);
2461 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192462 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552463 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362464 &d));
[email protected]f7022f32014-08-21 16:32:192465 req->Start();
[email protected]255620da2013-08-19 13:14:292466 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442467
2468 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2469 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2470 }
2471
2472 // Try to set-up another cookie and update the previous cookie.
2473 {
2474 TestNetworkDelegate network_delegate;
2475 default_context_.set_network_delegate(&network_delegate);
2476 TestDelegate d;
2477 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192478 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552479 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362480 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192481 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442482
[email protected]255620da2013-08-19 13:14:292483 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442484
2485 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2486 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2487 }
2488
2489 // Verify the cookies weren't saved or updated.
2490 {
2491 TestNetworkDelegate network_delegate;
2492 default_context_.set_network_delegate(&network_delegate);
2493 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192494 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552495 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192496 req->Start();
[email protected]255620da2013-08-19 13:14:292497 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442498
2499 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2500 == std::string::npos);
2501 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2502 != std::string::npos);
2503
2504 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2505 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2506 }
2507}
2508
2509TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2510 LocalHttpTestServer test_server;
2511 ASSERT_TRUE(test_server.Start());
2512
2513 // Set up an empty cookie.
2514 {
2515 TestNetworkDelegate network_delegate;
2516 default_context_.set_network_delegate(&network_delegate);
2517 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192518 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552519 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192520 req->Start();
[email protected]255620da2013-08-19 13:14:292521 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442522
2523 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2524 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2525 EXPECT_EQ(0, network_delegate.set_cookie_count());
2526 }
2527}
2528
2529TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2530 LocalHttpTestServer test_server;
2531 ASSERT_TRUE(test_server.Start());
2532
2533 // Set up a cookie.
2534 {
2535 TestNetworkDelegate network_delegate;
2536 default_context_.set_network_delegate(&network_delegate);
2537 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192538 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552539 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362540 &d));
[email protected]f7022f32014-08-21 16:32:192541 req->Start();
[email protected]255620da2013-08-19 13:14:292542 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442543
2544 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2545 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2546 }
2547
2548 // Verify that the cookie is set.
2549 {
2550 TestNetworkDelegate network_delegate;
2551 default_context_.set_network_delegate(&network_delegate);
2552 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192553 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552554 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192555 req->Start();
[email protected]255620da2013-08-19 13:14:292556 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442557
2558 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2559 != std::string::npos);
2560
2561 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2562 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2563 }
2564
2565 // Verify that the cookie isn't sent.
2566 {
2567 TestNetworkDelegate network_delegate;
2568 default_context_.set_network_delegate(&network_delegate);
2569 TestDelegate d;
2570 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192571 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552572 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192573 req->Start();
[email protected]255620da2013-08-19 13:14:292574 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442575
2576 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2577 == std::string::npos);
2578
[email protected]22e045f2013-09-20 03:54:032579 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442580 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2581 }
2582}
2583
2584TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2585 LocalHttpTestServer test_server;
2586 ASSERT_TRUE(test_server.Start());
2587
2588 // Set up a cookie.
2589 {
2590 TestNetworkDelegate network_delegate;
2591 default_context_.set_network_delegate(&network_delegate);
2592 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192593 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552594 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362595 &d));
[email protected]f7022f32014-08-21 16:32:192596 req->Start();
[email protected]255620da2013-08-19 13:14:292597 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442598
2599 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2600 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2601 }
2602
2603 // Try to set-up another cookie and update the previous cookie.
2604 {
2605 TestNetworkDelegate network_delegate;
2606 default_context_.set_network_delegate(&network_delegate);
2607 TestDelegate d;
2608 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192609 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552610 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362611 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192612 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442613
[email protected]255620da2013-08-19 13:14:292614 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442615
2616 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2617 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2618 }
2619
2620 // Verify the cookies weren't saved or updated.
2621 {
2622 TestNetworkDelegate network_delegate;
2623 default_context_.set_network_delegate(&network_delegate);
2624 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192625 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552626 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192627 req->Start();
[email protected]255620da2013-08-19 13:14:292628 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442629
2630 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2631 == std::string::npos);
2632 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2633 != std::string::npos);
2634
2635 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2636 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2637 }
2638}
2639
mkwst3f3daac2015-02-26 20:15:262640TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2641 LocalHttpTestServer test_server;
2642 ASSERT_TRUE(test_server.Start());
2643
2644 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2645 // LocalHttpTestServer points).
2646 {
2647 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412648 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262649 default_context_.set_network_delegate(&network_delegate);
2650
2651 TestDelegate d;
2652 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2653 test_server.GetURL(
tommycli59a63432015-11-06 00:10:552654 "/set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
davidben151423e2015-03-23 18:48:362655 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262656 req->Start();
2657 base::RunLoop().Run();
2658 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2659 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2660 EXPECT_EQ(1, network_delegate.set_cookie_count());
2661 }
2662
2663 // Verify that the cookie is sent for first-party requests.
2664 {
2665 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412666 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262667 default_context_.set_network_delegate(&network_delegate);
2668 TestDelegate d;
2669 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552670 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2671 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst3f3daac2015-02-26 20:15:262672 req->Start();
2673 base::RunLoop().Run();
2674
2675 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2676 std::string::npos);
2677 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2678 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2679 }
2680
2681 // Verify that the cookie is not-sent for non-first-party requests.
2682 {
2683 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412684 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262685 default_context_.set_network_delegate(&network_delegate);
2686 TestDelegate d;
2687 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552688 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262689 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2690 req->Start();
2691 base::RunLoop().Run();
2692
2693 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2694 std::string::npos);
2695 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2696 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2697 }
2698}
2699
mkwst0513c9d2015-04-01 05:53:152700TEST_F(URLRequestTest, FirstPartyOnlyCookiesDisabled) {
2701 LocalHttpTestServer test_server;
2702 ASSERT_TRUE(test_server.Start());
2703
2704 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2705 // LocalHttpTestServer points).
2706 {
2707 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412708 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152709 default_context_.set_network_delegate(&network_delegate);
2710
2711 TestDelegate d;
2712 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2713 test_server.GetURL(
tommycli59a63432015-11-06 00:10:552714 "/set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
mkwst0513c9d2015-04-01 05:53:152715 DEFAULT_PRIORITY, &d));
2716 req->Start();
2717 base::RunLoop().Run();
2718 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2719 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2720 EXPECT_EQ(1, network_delegate.set_cookie_count());
2721 }
2722
2723 // Verify that the cookie is sent for first-party requests.
2724 {
2725 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412726 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152727 default_context_.set_network_delegate(&network_delegate);
2728 TestDelegate d;
2729 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552730 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2731 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst0513c9d2015-04-01 05:53:152732 req->Start();
2733 base::RunLoop().Run();
2734
2735 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2736 std::string::npos);
2737 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2738 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2739 }
2740
2741 // Verify that the cookie is also sent for non-first-party requests.
2742 {
2743 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412744 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152745 default_context_.set_network_delegate(&network_delegate);
2746 TestDelegate d;
2747 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552748 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst0513c9d2015-04-01 05:53:152749 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2750 req->Start();
2751 base::RunLoop().Run();
2752
jww79aceda2015-12-07 01:56:342753 EXPECT_NE(d.data_received().find("FirstPartyCookieToSet=1"),
2754 std::string::npos);
mkwst0513c9d2015-04-01 05:53:152755 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2756 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2757 }
2758}
2759
estark557a5eb82015-12-01 22:57:102760// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:362761TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:552762 EmbeddedTestServer http_server;
2763 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362764 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552765 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2766 https_server.AddDefaultHandlers(
2767 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2768 ASSERT_TRUE(http_server.Start());
2769 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362770
2771 TestExperimentalFeaturesNetworkDelegate network_delegate;
2772 TestURLRequestContext context(true);
2773 context.set_network_delegate(&network_delegate);
2774 context.Init();
2775
estark557a5eb82015-12-01 22:57:102776 // Try to set a Secure __Secure- cookie, with experimental features
estarkcd39c11f2015-10-19 19:46:362777 // enabled.
2778 {
2779 TestDelegate d;
2780 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102781 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362782 DEFAULT_PRIORITY, &d));
2783 req->Start();
2784 base::RunLoop().Run();
2785 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2786 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2787 }
2788
2789 // Verify that the cookie is not set.
2790 {
2791 TestDelegate d;
2792 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552793 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362794 req->Start();
2795 base::RunLoop().Run();
2796
jww79aceda2015-12-07 01:56:342797 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
2798 std::string::npos);
estarkcd39c11f2015-10-19 19:46:362799 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2800 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2801 }
2802}
2803
2804TEST_F(URLRequestTest, SecureCookiePrefixNonexperimental) {
tommycli59a63432015-11-06 00:10:552805 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2806 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362807 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552808 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362809
2810 TestNetworkDelegate network_delegate;
2811 TestURLRequestContext context(true);
2812 context.set_network_delegate(&network_delegate);
2813 context.Init();
2814
2815 // Without experimental features, there should be no restrictions on
estark557a5eb82015-12-01 22:57:102816 // __Secure- cookies.
estarkcd39c11f2015-10-19 19:46:362817
estark557a5eb82015-12-01 22:57:102818 // Set a non-Secure cookie with the __Secure- prefix.
estarkcd39c11f2015-10-19 19:46:362819 {
2820 TestDelegate d;
2821 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102822 https_server.GetURL(
2823 "/set-cookie?__Secure-nonsecure-not-experimental=1"),
estarkcd39c11f2015-10-19 19:46:362824 DEFAULT_PRIORITY, &d));
2825 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
estark557a5eb82015-12-01 22:57:102831 // Set a Secure cookie with the __Secure- prefix.
estarkcd39c11f2015-10-19 19:46:362832 {
2833 TestDelegate d;
2834 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552835 https_server.GetURL(
estark557a5eb82015-12-01 22:57:102836 "/set-cookie?__Secure-secure-not-experimental=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362837 DEFAULT_PRIORITY, &d));
2838 req->Start();
2839 base::RunLoop().Run();
2840 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2841 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2842 }
2843
2844 // Verify that the cookies are set. Neither should have any
2845 // restrictions because the experimental flag is off.
2846 {
2847 TestDelegate d;
2848 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552849 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362850 req->Start();
2851 base::RunLoop().Run();
2852
jww79aceda2015-12-07 01:56:342853 EXPECT_NE(d.data_received().find("__Secure-secure-not-experimental=1"),
2854 std::string::npos);
2855 EXPECT_NE(d.data_received().find("__Secure-nonsecure-not-experimental=1"),
2856 std::string::npos);
estarkcd39c11f2015-10-19 19:46:362857 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2858 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2859 }
2860}
2861
2862TEST_F(URLRequestTest, SecureCookiePrefixExperimentalNonsecure) {
tommycli59a63432015-11-06 00:10:552863 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2864 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362865 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552866 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362867
2868 TestExperimentalFeaturesNetworkDelegate network_delegate;
2869 TestURLRequestContext context(true);
2870 context.set_network_delegate(&network_delegate);
2871 context.Init();
2872
estark557a5eb82015-12-01 22:57:102873 // Try to set a non-Secure __Secure- cookie, with experimental features
estarkcd39c11f2015-10-19 19:46:362874 // enabled.
2875 {
2876 TestDelegate d;
tommycli59a63432015-11-06 00:10:552877 scoped_ptr<URLRequest> req(
estark557a5eb82015-12-01 22:57:102878 context.CreateRequest(https_server.GetURL("/set-cookie?__Secure-foo=1"),
tommycli59a63432015-11-06 00:10:552879 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362880 req->Start();
2881 base::RunLoop().Run();
2882 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2883 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2884 }
2885
2886 // Verify that the cookie is not set.
2887 {
2888 TestDelegate d;
2889 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552890 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362891 req->Start();
2892 base::RunLoop().Run();
2893
jww79aceda2015-12-07 01:56:342894 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362895 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2896 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2897 }
2898}
2899
2900TEST_F(URLRequestTest, SecureCookiePrefixExperimentalSecure) {
tommycli59a63432015-11-06 00:10:552901 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2902 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362903 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552904 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362905
2906 TestExperimentalFeaturesNetworkDelegate network_delegate;
2907 TestURLRequestContext context(true);
2908 context.set_network_delegate(&network_delegate);
2909 context.Init();
2910
estark557a5eb82015-12-01 22:57:102911 // Try to set a Secure __Secure- cookie, with experimental features
estarkcd39c11f2015-10-19 19:46:362912 // enabled.
2913 {
2914 TestDelegate d;
2915 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102916 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
tommycli59a63432015-11-06 00:10:552917 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362918 req->Start();
2919 base::RunLoop().Run();
2920 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2921 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2922 }
2923
2924 // Verify that the cookie is set.
2925 {
2926 TestDelegate d;
2927 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552928 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362929 req->Start();
2930 base::RunLoop().Run();
2931
jww79aceda2015-12-07 01:56:342932 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
2933 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2934 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2935 }
2936}
2937
2938// Tests that secure cookies can't be set on non-secure origins if strict secure
2939// cookies are enabled.
2940TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
2941 EmbeddedTestServer http_server;
2942 http_server.AddDefaultHandlers(
2943 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2944 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2945 https_server.AddDefaultHandlers(
2946 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2947 ASSERT_TRUE(http_server.Start());
2948 ASSERT_TRUE(https_server.Start());
2949
2950 TestExperimentalFeaturesNetworkDelegate network_delegate;
2951 TestURLRequestContext context(true);
2952 context.set_network_delegate(&network_delegate);
2953 context.Init();
2954
2955 // Try to set a Secure cookie, with experimental features enabled.
2956 {
2957 TestDelegate d;
2958 scoped_ptr<URLRequest> req(context.CreateRequest(
2959 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
2960 DEFAULT_PRIORITY, &d));
2961 req->Start();
2962 base::RunLoop().Run();
2963 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2964 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2965 }
2966
2967 // Verify that the cookie is not set.
2968 {
2969 TestDelegate d;
2970 scoped_ptr<URLRequest> req(context.CreateRequest(
2971 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2972 req->Start();
2973 base::RunLoop().Run();
2974
2975 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
2976 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2977 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2978 }
2979}
2980
2981// Tests that secure cookies can be set on secure origins even if strict secure
2982// cookies are enabled.
2983TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
2984 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2985 https_server.AddDefaultHandlers(
2986 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2987 ASSERT_TRUE(https_server.Start());
2988
2989 TestExperimentalFeaturesNetworkDelegate network_delegate;
2990 TestURLRequestContext context(true);
2991 context.set_network_delegate(&network_delegate);
2992 context.Init();
2993
2994 // Try to set a Secure cookie, with experimental features enabled.
2995 {
2996 TestDelegate d;
2997 scoped_ptr<URLRequest> req(context.CreateRequest(
2998 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
2999 DEFAULT_PRIORITY, &d));
3000 req->Start();
3001 base::RunLoop().Run();
3002 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3003 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3004 }
3005
3006 // Verify that the cookie is not set.
3007 {
3008 TestDelegate d;
3009 scoped_ptr<URLRequest> req(context.CreateRequest(
3010 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
3011 req->Start();
3012 base::RunLoop().Run();
3013
3014 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363015 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3016 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3017 }
3018}
3019
mmenkefb18c772015-09-30 22:22:503020// Tests that a request is cancelled while entering suspend mode. Uses mocks
3021// rather than a spawned test server because the connection used to talk to
3022// the test server is affected by entering suspend mode on Android.
3023TEST_F(URLRequestTest, CancelOnSuspend) {
3024 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
3025 base::PowerMonitor power_monitor(make_scoped_ptr(power_monitor_source));
3026
3027 URLRequestFailedJob::AddUrlHandler();
3028
3029 TestDelegate d;
3030 // Request that just hangs.
3031 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
3032 scoped_ptr<URLRequest> r(
3033 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
3034 r->Start();
3035
3036 power_monitor_source->Suspend();
3037 // Wait for the suspend notification to cause the request to fail.
3038 base::RunLoop().Run();
3039 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3040 EXPECT_TRUE(d.request_failed());
3041 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3042
3043 URLRequestFilter::GetInstance()->ClearHandlers();
3044
3045 // Shouldn't be needed, but just in case.
3046 power_monitor_source->Resume();
3047}
3048
[email protected]5095cd72012-11-01 10:29:163049// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3050// value for the |fixed_date| argument given to the constructor.
3051class FixedDateNetworkDelegate : public TestNetworkDelegate {
3052 public:
3053 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3054 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:203055 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163056
[email protected]cba24642014-08-15 20:49:593057 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203058 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593059 URLRequest* request,
3060 const CompletionCallback& callback,
3061 const HttpResponseHeaders* original_response_headers,
3062 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133063 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163064
3065 private:
3066 std::string fixed_date_;
3067
3068 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3069};
3070
3071int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593072 URLRequest* request,
3073 const CompletionCallback& callback,
3074 const HttpResponseHeaders* original_response_headers,
3075 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163076 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593077 HttpResponseHeaders* new_response_headers =
3078 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163079
3080 new_response_headers->RemoveHeader("Date");
3081 new_response_headers->AddHeader("Date: " + fixed_date_);
3082
3083 *override_response_headers = new_response_headers;
3084 return TestNetworkDelegate::OnHeadersReceived(request,
3085 callback,
3086 original_response_headers,
[email protected]5f714132014-03-26 10:41:163087 override_response_headers,
3088 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163089}
3090
3091// Test that cookie expiration times are adjusted for server/client clock
3092// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3093// headers by defaulting to GMT. (crbug.com/135131)
3094TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3095 LocalHttpTestServer test_server;
3096 ASSERT_TRUE(test_server.Start());
3097
3098 // Set up an expired cookie.
3099 {
3100 TestNetworkDelegate network_delegate;
3101 default_context_.set_network_delegate(&network_delegate);
3102 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193103 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193104 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553105 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363106 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193107 req->Start();
[email protected]255620da2013-08-19 13:14:293108 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163109 }
3110 // Verify that the cookie is not set.
3111 {
3112 TestNetworkDelegate network_delegate;
3113 default_context_.set_network_delegate(&network_delegate);
3114 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193115 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553116 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193117 req->Start();
[email protected]255620da2013-08-19 13:14:293118 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163119
3120 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3121 }
3122 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3123 {
3124 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3125 default_context_.set_network_delegate(&network_delegate);
3126 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193127 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193128 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553129 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363130 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193131 req->Start();
[email protected]255620da2013-08-19 13:14:293132 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163133 }
3134 // Verify that the cookie is set.
3135 {
3136 TestNetworkDelegate network_delegate;
3137 default_context_.set_network_delegate(&network_delegate);
3138 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193139 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553140 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193141 req->Start();
[email protected]255620da2013-08-19 13:14:293142 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163143
3144 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3145 }
3146}
3147
3148
[email protected]316c1e5e2012-09-12 15:17:443149// Check that it is impossible to change the referrer in the extra headers of
3150// an URLRequest.
3151TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3152 LocalHttpTestServer test_server;
3153 ASSERT_TRUE(test_server.Start());
3154
3155 // If extra headers contain referer and the request contains a referer,
3156 // only the latter shall be respected.
3157 {
3158 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193159 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553160 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193161 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443162
3163 HttpRequestHeaders headers;
3164 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193165 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443166
[email protected]f7022f32014-08-21 16:32:193167 req->Start();
[email protected]255620da2013-08-19 13:14:293168 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443169
3170 EXPECT_EQ("http://foo.com/", d.data_received());
3171 }
3172
3173 // If extra headers contain a referer but the request does not, no referer
3174 // shall be sent in the header.
3175 {
3176 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193177 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553178 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443179
3180 HttpRequestHeaders headers;
3181 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193182 req->SetExtraRequestHeaders(headers);
3183 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443184
[email protected]f7022f32014-08-21 16:32:193185 req->Start();
[email protected]255620da2013-08-19 13:14:293186 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443187
3188 EXPECT_EQ("None", d.data_received());
3189 }
3190}
3191
[email protected]b89290212009-08-14 22:37:353192class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113193 public:
mmenke9f2ec60c2015-06-01 20:59:473194 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113195
[email protected]b89290212009-08-14 22:37:353196 protected:
[email protected]21184962011-10-26 00:50:303197 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3198 // |request_method| is the method to use for the initial request.
3199 // |redirect_method| is the method that is expected to be used for the second
3200 // request, after redirection.
3201 // If |include_data| is true, data is uploaded with the request. The
3202 // response body is expected to match it exactly, if and only if
3203 // |request_method| == |redirect_method|.
3204 void HTTPRedirectMethodTest(const GURL& redirect_url,
3205 const std::string& request_method,
3206 const std::string& redirect_method,
3207 bool include_data) {
3208 static const char kData[] = "hello world";
3209 TestDelegate d;
davidben151423e2015-03-23 18:48:363210 scoped_ptr<URLRequest> req(
3211 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193212 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303213 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073214 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303215 HttpRequestHeaders headers;
3216 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513217 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543218 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193219 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303220 }
[email protected]f7022f32014-08-21 16:32:193221 req->Start();
[email protected]255620da2013-08-19 13:14:293222 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193223 EXPECT_EQ(redirect_method, req->method());
3224 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
3225 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:303226 if (include_data) {
3227 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543228 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3229 HttpRequestHeaders::kContentLength));
3230 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3231 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303232 EXPECT_EQ(kData, d.data_received());
3233 } else {
svaldez5b3a8972015-10-09 23:23:543234 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3235 HttpRequestHeaders::kContentLength));
3236 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3237 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303238 EXPECT_NE(kData, d.data_received());
3239 }
3240 }
3241 if (HasFailure())
3242 LOG(WARNING) << "Request method was: " << request_method;
3243 }
3244
jww5fe460ff2015-03-28 00:22:513245 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3246 // |request_method| is the method to use for the initial request.
3247 // |redirect_method| is the method that is expected to be used for the second
3248 // request, after redirection.
3249 // |origin_value| is the expected value for the Origin header after
3250 // redirection. If empty, expects that there will be no Origin header.
3251 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3252 const std::string& request_method,
3253 const std::string& redirect_method,
3254 const std::string& origin_value) {
3255 TestDelegate d;
3256 scoped_ptr<URLRequest> req(
3257 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3258 req->set_method(request_method);
3259 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3260 redirect_url.GetOrigin().spec(), false);
3261 req->Start();
3262
3263 base::RunLoop().Run();
3264
3265 EXPECT_EQ(redirect_method, req->method());
3266 // Note that there is no check for request success here because, for
3267 // purposes of testing, the request very well may fail. For example, if the
3268 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3269 // origin, there is not an HTTPS server in this unit test framework, so the
3270 // request would fail. However, that's fine, as long as the request headers
3271 // are in order and pass the checks below.
3272 if (origin_value.empty()) {
3273 EXPECT_FALSE(
3274 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3275 } else {
3276 std::string origin_header;
3277 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3278 HttpRequestHeaders::kOrigin, &origin_header));
3279 EXPECT_EQ(origin_value, origin_header);
3280 }
3281 }
3282
[email protected]762d2db2010-01-11 19:03:013283 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013284 const int kMsgSize = 20000; // multiple of 10
3285 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483286 char* uploadBytes = new char[kMsgSize+1];
3287 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013288 char marker = 'a';
3289 for (int idx = 0; idx < kMsgSize/10; idx++) {
3290 memcpy(ptr, "----------", 10);
3291 ptr += 10;
3292 if (idx % 100 == 0) {
3293 ptr--;
3294 *ptr++ = marker;
3295 if (++marker > 'z')
3296 marker = 'a';
3297 }
3298 }
3299 uploadBytes[kMsgSize] = '\0';
3300
[email protected]762d2db2010-01-11 19:03:013301 for (int i = 0; i < kIterations; ++i) {
3302 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193303 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553304 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193305 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013306
mmenkecbc2b712014-10-09 20:29:073307 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013308
[email protected]f7022f32014-08-21 16:32:193309 r->Start();
3310 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013311
[email protected]255620da2013-08-19 13:14:293312 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013313
[email protected]329b68b2012-11-14 17:54:273314 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:193315 << "request failed: " << r->status().status()
3316 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:013317
3318 EXPECT_FALSE(d.received_data_before_response());
3319 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013320 }
3321 delete[] uploadBytes;
3322 }
3323
[email protected]ef2bf422012-05-11 03:27:093324 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:223325 r->AppendChunkToUpload("a", 1, false);
3326 r->AppendChunkToUpload("bcd", 3, false);
3327 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
3328 r->AppendChunkToUpload("\r\n\r\n", 4, false);
3329 r->AppendChunkToUpload("0", 1, false);
3330 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:113331 }
3332
[email protected]ef2bf422012-05-11 03:27:093333 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:113334 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:273335 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:113336 "abcdthis is a longer chunk than before.\r\n\r\n02323";
3337
[email protected]329b68b2012-11-14 17:54:273338 ASSERT_EQ(1, d->response_started_count())
3339 << "request failed: " << r->status().status()
3340 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:113341
3342 EXPECT_FALSE(d->received_data_before_response());
3343
[email protected]329b68b2012-11-14 17:54:273344 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
3345 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:113346 }
3347
[email protected]ede03212012-09-07 12:52:263348 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343349 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193350 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553351 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363352 base::IntToString(num_cookies)),
3353 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343354
[email protected]f7022f32014-08-21 16:32:193355 r->Start();
3356 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343357
[email protected]255620da2013-08-19 13:14:293358 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343359
[email protected]f7022f32014-08-21 16:32:193360 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:343361
tommycli59a63432015-11-06 00:10:553362 if (!is_success)
[email protected]f7022f32014-08-21 16:32:193363 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:343364
3365 return is_success;
3366 }
3367
tommycli59a63432015-11-06 00:10:553368 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503369
tommycli59a63432015-11-06 00:10:553370 private:
[email protected]1700c6a2012-02-22 18:07:073371 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353372};
3373
tommycli59a63432015-11-06 00:10:553374namespace {
3375
3376scoped_ptr<test_server::HttpResponse> HandleRedirectConnect(
3377 const test_server::HttpRequest& request) {
3378 if (request.headers.find("Host") == request.headers.end() ||
3379 request.headers.at("Host") != "www.redirect.com" ||
3380 request.method != test_server::METHOD_CONNECT) {
3381 return nullptr;
3382 }
3383
3384 scoped_ptr<test_server::BasicHttpResponse> http_response(
3385 new test_server::BasicHttpResponse);
3386 http_response->set_code(HTTP_FOUND);
3387 http_response->AddCustomHeader("Location",
3388 "http://www.destination.com/foo.js");
3389 return http_response.Pass();
3390}
3391
3392} // namespace
3393
3394// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113395// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553396// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113397// follow.
[email protected]f2f31b32013-01-16 23:24:093398TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553399 http_test_server()->RegisterRequestHandler(
3400 base::Bind(&HandleRedirectConnect));
3401 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113402
[email protected]ceefd7fd2012-11-29 00:36:243403 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043404 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553405 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503406
[email protected]d1ec59082009-02-11 02:48:153407 TestDelegate d;
3408 {
[email protected]f7022f32014-08-21 16:32:193409 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363410 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193411 r->Start();
3412 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153413
[email protected]255620da2013-08-19 13:14:293414 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153415
[email protected]f7022f32014-08-21 16:32:193416 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153417 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193418 EXPECT_TRUE(r->proxy_server().IsEmpty());
3419 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083420 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153421 // We should not have followed the redirect.
3422 EXPECT_EQ(0, d.received_redirect_count());
3423 }
3424}
3425
[email protected]8202d0c2011-02-23 08:31:143426// This is the same as the previous test, but checks that the network delegate
3427// registers the error.
[email protected]c044616e2013-02-20 02:01:263428TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553429 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143430
[email protected]ceefd7fd2012-11-29 00:36:243431 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043432 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553433 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503434
[email protected]8202d0c2011-02-23 08:31:143435 TestDelegate d;
3436 {
[email protected]f7022f32014-08-21 16:32:193437 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363438 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193439 r->Start();
3440 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143441
[email protected]255620da2013-08-19 13:14:293442 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143443
[email protected]f7022f32014-08-21 16:32:193444 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153445 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193446 EXPECT_TRUE(r->proxy_server().IsEmpty());
3447 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143448 EXPECT_EQ(1, d.response_started_count());
3449 // We should not have followed the redirect.
3450 EXPECT_EQ(0, d.received_redirect_count());
3451
3452 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053453 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143454 }
3455}
3456
[email protected]dc5a5cf2012-09-26 02:49:303457// Tests that we can block and asynchronously return OK in various stages.
3458TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3459 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3460 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3461 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3462 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3463 };
3464 static const size_t blocking_stages_length = arraysize(blocking_stages);
3465
tommycli59a63432015-11-06 00:10:553466 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:303467
3468 TestDelegate d;
3469 BlockingNetworkDelegate network_delegate(
3470 BlockingNetworkDelegate::USER_CALLBACK);
3471 network_delegate.set_block_on(
3472 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3473 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3474 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3475
3476 TestURLRequestContext context(true);
3477 context.set_network_delegate(&network_delegate);
3478 context.Init();
3479
3480 {
[email protected]f7022f32014-08-21 16:32:193481 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553482 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303483
[email protected]f7022f32014-08-21 16:32:193484 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303485 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293486 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303487 EXPECT_EQ(blocking_stages[i],
3488 network_delegate.stage_blocked_for_callback());
3489 network_delegate.DoCallback(OK);
3490 }
[email protected]255620da2013-08-19 13:14:293491 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193492 EXPECT_EQ(200, r->GetResponseCode());
3493 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303494 EXPECT_EQ(1, network_delegate.created_requests());
3495 EXPECT_EQ(0, network_delegate.destroyed_requests());
3496 }
3497 EXPECT_EQ(1, network_delegate.destroyed_requests());
3498}
3499
[email protected]4c76d7c2011-04-15 19:14:123500// Tests that the network delegate can block and cancel a request.
3501TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:553502 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123503
3504 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303505 BlockingNetworkDelegate network_delegate(
3506 BlockingNetworkDelegate::AUTO_CALLBACK);
3507 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3508 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123509
[email protected]d5a4dd62012-05-23 01:41:043510 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553511 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503512
[email protected]4c76d7c2011-04-15 19:14:123513 {
[email protected]f7022f32014-08-21 16:32:193514 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553515 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123516
[email protected]f7022f32014-08-21 16:32:193517 r->Start();
[email protected]255620da2013-08-19 13:14:293518 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123519
[email protected]f7022f32014-08-21 16:32:193520 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153521 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193522 EXPECT_TRUE(r->proxy_server().IsEmpty());
3523 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123524 EXPECT_EQ(1, network_delegate.created_requests());
3525 EXPECT_EQ(0, network_delegate.destroyed_requests());
3526 }
3527 EXPECT_EQ(1, network_delegate.destroyed_requests());
3528}
3529
[email protected]b4438d32012-09-27 06:15:303530// Helper function for NetworkDelegateCancelRequestAsynchronously and
3531// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3532// delegate operating in |block_mode| and a request for |url|. It blocks the
3533// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3534void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3535 BlockingNetworkDelegate::Stage stage,
3536 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363537 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303538 BlockingNetworkDelegate network_delegate(block_mode);
3539 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3540 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363541
[email protected]b4438d32012-09-27 06:15:303542 TestURLRequestContext context(true);
3543 context.set_network_delegate(&network_delegate);
3544 context.Init();
[email protected]3cd384c602011-08-31 16:12:363545
3546 {
davidben151423e2015-03-23 18:48:363547 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363548
[email protected]f7022f32014-08-21 16:32:193549 r->Start();
[email protected]255620da2013-08-19 13:14:293550 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363551
[email protected]f7022f32014-08-21 16:32:193552 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153553 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193554 EXPECT_TRUE(r->proxy_server().IsEmpty());
3555 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363556 EXPECT_EQ(1, network_delegate.created_requests());
3557 EXPECT_EQ(0, network_delegate.destroyed_requests());
3558 }
3559 EXPECT_EQ(1, network_delegate.destroyed_requests());
3560}
3561
[email protected]b4438d32012-09-27 06:15:303562// The following 3 tests check that the network delegate can cancel a request
3563// synchronously in various stages of the request.
3564TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:553565 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303566 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3567 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553568 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303569}
3570
3571TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:553572 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303573 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3574 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553575 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303576}
3577
3578TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:553579 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303580 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3581 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553582 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303583}
3584
3585// The following 3 tests check that the network delegate can cancel a request
3586// asynchronously in various stages of the request.
3587TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:553588 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303589 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3590 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553591 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303592}
3593
3594TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:553595 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303596 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3597 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553598 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303599}
3600
3601TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:553602 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303603 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3604 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553605 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303606}
3607
[email protected]4c76d7c2011-04-15 19:14:123608// Tests that the network delegate can block and redirect a request to a new
3609// URL.
3610TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:553611 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123612
3613 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303614 BlockingNetworkDelegate network_delegate(
3615 BlockingNetworkDelegate::AUTO_CALLBACK);
3616 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553617 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:123618 network_delegate.set_redirect_url(redirect_url);
3619
[email protected]d5a4dd62012-05-23 01:41:043620 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553621 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503622
[email protected]4c76d7c2011-04-15 19:14:123623 {
tommycli59a63432015-11-06 00:10:553624 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363625 scoped_ptr<URLRequest> r(
3626 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123627
[email protected]6be6fa92014-08-06 23:44:563628 // Quit after hitting the redirect, so can check the headers.
3629 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193630 r->Start();
[email protected]255620da2013-08-19 13:14:293631 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123632
[email protected]6be6fa92014-08-06 23:44:563633 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193634 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3635 EXPECT_EQ(307, r->GetResponseCode());
3636 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563637 std::string location;
[email protected]f7022f32014-08-21 16:32:193638 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3639 &location));
[email protected]6be6fa92014-08-06 23:44:563640 EXPECT_EQ(redirect_url, GURL(location));
3641
3642 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193643 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563644 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193645 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553646 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273647 EXPECT_EQ(
3648 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553649 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3650 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273651
[email protected]f7022f32014-08-21 16:32:193652 EXPECT_EQ(0, r->status().error());
3653 EXPECT_EQ(redirect_url, r->url());
3654 EXPECT_EQ(original_url, r->original_url());
3655 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123656 EXPECT_EQ(1, network_delegate.created_requests());
3657 EXPECT_EQ(0, network_delegate.destroyed_requests());
3658 }
3659 EXPECT_EQ(1, network_delegate.destroyed_requests());
3660}
3661
[email protected]b813ed72012-04-05 08:21:363662// Tests that the network delegate can block and redirect a request to a new
3663// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3664TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:553665 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:363666
3667 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303668 BlockingNetworkDelegate network_delegate(
3669 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:553670 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:363671 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363672
[email protected]d5a4dd62012-05-23 01:41:043673 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553674 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363675
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]b813ed72012-04-05 08:21:363680
[email protected]6be6fa92014-08-06 23:44:563681 // Quit after hitting the redirect, so can check the headers.
3682 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193683 r->Start();
[email protected]255620da2013-08-19 13:14:293684 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363685
[email protected]6be6fa92014-08-06 23:44:563686 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193687 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3688 EXPECT_EQ(307, r->GetResponseCode());
3689 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563690 std::string location;
[email protected]f7022f32014-08-21 16:32:193691 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3692 &location));
[email protected]6be6fa92014-08-06 23:44:563693 EXPECT_EQ(redirect_url, GURL(location));
3694
3695 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193696 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563697 base::RunLoop().Run();
3698
[email protected]f7022f32014-08-21 16:32:193699 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553700 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273701 EXPECT_EQ(
3702 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553703 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3704 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193705 EXPECT_EQ(0, r->status().error());
3706 EXPECT_EQ(redirect_url, r->url());
3707 EXPECT_EQ(original_url, r->original_url());
3708 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363709 EXPECT_EQ(1, network_delegate.created_requests());
3710 EXPECT_EQ(0, network_delegate.destroyed_requests());
3711 }
3712 EXPECT_EQ(1, network_delegate.destroyed_requests());
3713}
3714
[email protected]3c5ca8c2011-09-29 01:14:513715// Tests that redirects caused by the network delegate preserve POST data.
3716TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:553717 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:513718
3719 const char kData[] = "hello world";
3720
3721 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303722 BlockingNetworkDelegate network_delegate(
3723 BlockingNetworkDelegate::AUTO_CALLBACK);
3724 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553725 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:513726 network_delegate.set_redirect_url(redirect_url);
3727
[email protected]ef2bf422012-05-11 03:27:093728 TestURLRequestContext context(true);
3729 context.set_network_delegate(&network_delegate);
3730 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513731
3732 {
tommycli59a63432015-11-06 00:10:553733 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363734 scoped_ptr<URLRequest> r(
3735 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193736 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073737 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513738 HttpRequestHeaders headers;
3739 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513740 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193741 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563742
3743 // Quit after hitting the redirect, so can check the headers.
3744 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193745 r->Start();
[email protected]255620da2013-08-19 13:14:293746 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513747
[email protected]6be6fa92014-08-06 23:44:563748 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193749 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3750 EXPECT_EQ(307, r->GetResponseCode());
3751 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563752 std::string location;
[email protected]f7022f32014-08-21 16:32:193753 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3754 &location));
[email protected]6be6fa92014-08-06 23:44:563755 EXPECT_EQ(redirect_url, GURL(location));
3756
3757 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193758 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563759 base::RunLoop().Run();
3760
[email protected]f7022f32014-08-21 16:32:193761 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3762 EXPECT_EQ(0, r->status().error());
3763 EXPECT_EQ(redirect_url, r->url());
3764 EXPECT_EQ(original_url, r->original_url());
3765 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513766 EXPECT_EQ(1, network_delegate.created_requests());
3767 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193768 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513769 EXPECT_EQ(kData, d.data_received());
3770 }
3771 EXPECT_EQ(1, network_delegate.destroyed_requests());
3772}
3773
[email protected]5f714132014-03-26 10:41:163774// Tests that the network delegate can block and redirect a request to a new
3775// URL during OnHeadersReceived.
3776TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:553777 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:163778
3779 TestDelegate d;
3780 BlockingNetworkDelegate network_delegate(
3781 BlockingNetworkDelegate::AUTO_CALLBACK);
3782 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:553783 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:163784 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3785
3786 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553787 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:163788
3789 {
tommycli59a63432015-11-06 00:10:553790 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363791 scoped_ptr<URLRequest> r(
3792 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163793
[email protected]f7022f32014-08-21 16:32:193794 r->Start();
[email protected]5f714132014-03-26 10:41:163795 base::RunLoop().Run();
3796
[email protected]f7022f32014-08-21 16:32:193797 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553798 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273799 EXPECT_EQ(
3800 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553801 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3802 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193803
3804 EXPECT_EQ(OK, r->status().error());
3805 EXPECT_EQ(redirect_url, r->url());
3806 EXPECT_EQ(original_url, r->original_url());
3807 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163808 EXPECT_EQ(2, network_delegate.created_requests());
3809 EXPECT_EQ(0, network_delegate.destroyed_requests());
3810 }
3811 EXPECT_EQ(1, network_delegate.destroyed_requests());
3812}
3813
[email protected]c2911d72011-10-03 22:16:363814// Tests that the network delegate can synchronously complete OnAuthRequired
3815// by taking no action. This indicates that the NetworkDelegate does not want to
3816// handle the challenge, and is passing the buck along to the
3817// URLRequest::Delegate.
3818TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:553819 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363820
3821 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303822 BlockingNetworkDelegate network_delegate(
3823 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363824
[email protected]ef2bf422012-05-11 03:27:093825 TestURLRequestContext context(true);
3826 context.set_network_delegate(&network_delegate);
3827 context.Init();
[email protected]c2911d72011-10-03 22:16:363828
[email protected]f3cf9802011-10-28 18:44:583829 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363830
3831 {
tommycli59a63432015-11-06 00:10:553832 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363833 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193834 r->Start();
[email protected]79e1fd62013-06-20 06:50:043835
[email protected]255620da2013-08-19 13:14:293836 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043837
[email protected]f7022f32014-08-21 16:32:193838 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3839 EXPECT_EQ(0, r->status().error());
3840 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043841 EXPECT_TRUE(d.auth_required_called());
3842 EXPECT_EQ(1, network_delegate.created_requests());
3843 EXPECT_EQ(0, network_delegate.destroyed_requests());
3844 }
3845 EXPECT_EQ(1, network_delegate.destroyed_requests());
3846}
3847
3848TEST_F(URLRequestTestHTTP,
3849 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:553850 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:043851
3852 TestDelegate d;
3853 BlockingNetworkDelegate network_delegate(
3854 BlockingNetworkDelegate::SYNCHRONOUS);
3855
3856 TestURLRequestContext context(true);
3857 context.set_network_delegate(&network_delegate);
3858 context.Init();
3859
3860 d.set_credentials(AuthCredentials(kUser, kSecret));
3861
3862 {
tommycli59a63432015-11-06 00:10:553863 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363864 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193865 r->Start();
[email protected]79e1fd62013-06-20 06:50:043866
3867 {
3868 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193869 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043870 EXPECT_FALSE(headers.HasHeader("Authorization"));
3871 }
3872
[email protected]255620da2013-08-19 13:14:293873 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363874
[email protected]f7022f32014-08-21 16:32:193875 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3876 EXPECT_EQ(0, r->status().error());
3877 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363878 EXPECT_TRUE(d.auth_required_called());
3879 EXPECT_EQ(1, network_delegate.created_requests());
3880 EXPECT_EQ(0, network_delegate.destroyed_requests());
3881 }
3882 EXPECT_EQ(1, network_delegate.destroyed_requests());
3883}
3884
3885// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403886// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363887TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:553888 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363889
3890 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303891 BlockingNetworkDelegate network_delegate(
3892 BlockingNetworkDelegate::SYNCHRONOUS);
3893 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363894 network_delegate.set_auth_retval(
3895 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3896
[email protected]f3cf9802011-10-28 18:44:583897 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363898
[email protected]ef2bf422012-05-11 03:27:093899 TestURLRequestContext context(true);
3900 context.set_network_delegate(&network_delegate);
3901 context.Init();
[email protected]c2911d72011-10-03 22:16:363902
3903 {
tommycli59a63432015-11-06 00:10:553904 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363905 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193906 r->Start();
[email protected]255620da2013-08-19 13:14:293907 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363908
[email protected]f7022f32014-08-21 16:32:193909 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3910 EXPECT_EQ(0, r->status().error());
3911 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363912 EXPECT_FALSE(d.auth_required_called());
3913 EXPECT_EQ(1, network_delegate.created_requests());
3914 EXPECT_EQ(0, network_delegate.destroyed_requests());
3915 }
3916 EXPECT_EQ(1, network_delegate.destroyed_requests());
3917}
3918
[email protected]79e1fd62013-06-20 06:50:043919// Same as above, but also tests that GetFullRequestHeaders returns the proper
3920// headers (for the first or second request) when called at the proper times.
3921TEST_F(URLRequestTestHTTP,
3922 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:553923 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:043924
3925 TestDelegate d;
3926 BlockingNetworkDelegate network_delegate(
3927 BlockingNetworkDelegate::SYNCHRONOUS);
3928 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3929 network_delegate.set_auth_retval(
3930 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3931
3932 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3933
3934 TestURLRequestContext context(true);
3935 context.set_network_delegate(&network_delegate);
3936 context.Init();
3937
3938 {
tommycli59a63432015-11-06 00:10:553939 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363940 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193941 r->Start();
[email protected]255620da2013-08-19 13:14:293942 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043943
[email protected]f7022f32014-08-21 16:32:193944 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3945 EXPECT_EQ(0, r->status().error());
3946 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043947 EXPECT_FALSE(d.auth_required_called());
3948 EXPECT_EQ(1, network_delegate.created_requests());
3949 EXPECT_EQ(0, network_delegate.destroyed_requests());
3950
3951 {
3952 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193953 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043954 EXPECT_TRUE(headers.HasHeader("Authorization"));
3955 }
3956 }
3957 EXPECT_EQ(1, network_delegate.destroyed_requests());
3958}
3959
[email protected]c2911d72011-10-03 22:16:363960// Tests that the network delegate can synchronously complete OnAuthRequired
3961// by cancelling authentication.
3962TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:553963 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363964
3965 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303966 BlockingNetworkDelegate network_delegate(
3967 BlockingNetworkDelegate::SYNCHRONOUS);
3968 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363969 network_delegate.set_auth_retval(
3970 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3971
[email protected]ef2bf422012-05-11 03:27:093972 TestURLRequestContext context(true);
3973 context.set_network_delegate(&network_delegate);
3974 context.Init();
[email protected]c2911d72011-10-03 22:16:363975
3976 {
tommycli59a63432015-11-06 00:10:553977 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363978 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193979 r->Start();
[email protected]255620da2013-08-19 13:14:293980 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363981
[email protected]f7022f32014-08-21 16:32:193982 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3983 EXPECT_EQ(OK, r->status().error());
3984 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363985 EXPECT_FALSE(d.auth_required_called());
3986 EXPECT_EQ(1, network_delegate.created_requests());
3987 EXPECT_EQ(0, network_delegate.destroyed_requests());
3988 }
3989 EXPECT_EQ(1, network_delegate.destroyed_requests());
3990}
3991
3992// Tests that the network delegate can asynchronously complete OnAuthRequired
3993// by taking no action. This indicates that the NetworkDelegate does not want
3994// to handle the challenge, and is passing the buck along to the
3995// URLRequest::Delegate.
3996TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:553997 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363998
3999 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304000 BlockingNetworkDelegate network_delegate(
4001 BlockingNetworkDelegate::AUTO_CALLBACK);
4002 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364003
[email protected]ef2bf422012-05-11 03:27:094004 TestURLRequestContext context(true);
4005 context.set_network_delegate(&network_delegate);
4006 context.Init();
[email protected]c2911d72011-10-03 22:16:364007
[email protected]f3cf9802011-10-28 18:44:584008 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364009
4010 {
tommycli59a63432015-11-06 00:10:554011 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364012 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194013 r->Start();
[email protected]255620da2013-08-19 13:14:294014 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364015
[email protected]f7022f32014-08-21 16:32:194016 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4017 EXPECT_EQ(0, r->status().error());
4018 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364019 EXPECT_TRUE(d.auth_required_called());
4020 EXPECT_EQ(1, network_delegate.created_requests());
4021 EXPECT_EQ(0, network_delegate.destroyed_requests());
4022 }
4023 EXPECT_EQ(1, network_delegate.destroyed_requests());
4024}
4025
4026// Tests that the network delegate can asynchronously complete OnAuthRequired
4027// by setting credentials.
4028TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554029 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364030
4031 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304032 BlockingNetworkDelegate network_delegate(
4033 BlockingNetworkDelegate::AUTO_CALLBACK);
4034 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364035 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364036 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4037
[email protected]f3cf9802011-10-28 18:44:584038 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364039 network_delegate.set_auth_credentials(auth_credentials);
4040
[email protected]ef2bf422012-05-11 03:27:094041 TestURLRequestContext context(true);
4042 context.set_network_delegate(&network_delegate);
4043 context.Init();
[email protected]c2911d72011-10-03 22:16:364044
4045 {
tommycli59a63432015-11-06 00:10:554046 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364047 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194048 r->Start();
[email protected]255620da2013-08-19 13:14:294049 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364050
[email protected]f7022f32014-08-21 16:32:194051 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4052 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:364053
[email protected]f7022f32014-08-21 16:32:194054 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364055 EXPECT_FALSE(d.auth_required_called());
4056 EXPECT_EQ(1, network_delegate.created_requests());
4057 EXPECT_EQ(0, network_delegate.destroyed_requests());
4058 }
4059 EXPECT_EQ(1, network_delegate.destroyed_requests());
4060}
4061
4062// Tests that the network delegate can asynchronously complete OnAuthRequired
4063// by cancelling authentication.
4064TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554065 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364066
4067 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304068 BlockingNetworkDelegate network_delegate(
4069 BlockingNetworkDelegate::AUTO_CALLBACK);
4070 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364071 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364072 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4073
[email protected]ef2bf422012-05-11 03:27:094074 TestURLRequestContext context(true);
4075 context.set_network_delegate(&network_delegate);
4076 context.Init();
[email protected]c2911d72011-10-03 22:16:364077
4078 {
tommycli59a63432015-11-06 00:10:554079 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364080 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194081 r->Start();
[email protected]255620da2013-08-19 13:14:294082 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364083
[email protected]f7022f32014-08-21 16:32:194084 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4085 EXPECT_EQ(OK, r->status().error());
4086 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364087 EXPECT_FALSE(d.auth_required_called());
4088 EXPECT_EQ(1, network_delegate.created_requests());
4089 EXPECT_EQ(0, network_delegate.destroyed_requests());
4090 }
4091 EXPECT_EQ(1, network_delegate.destroyed_requests());
4092}
4093
[email protected]9045b8822012-01-13 20:35:354094// Tests that we can handle when a network request was canceled while we were
4095// waiting for the network delegate.
4096// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4097TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554098 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354099
4100 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304101 BlockingNetworkDelegate network_delegate(
4102 BlockingNetworkDelegate::USER_CALLBACK);
4103 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354104
[email protected]ef2bf422012-05-11 03:27:094105 TestURLRequestContext context(true);
4106 context.set_network_delegate(&network_delegate);
4107 context.Init();
[email protected]9045b8822012-01-13 20:35:354108
4109 {
[email protected]f7022f32014-08-21 16:32:194110 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554111 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354112
[email protected]f7022f32014-08-21 16:32:194113 r->Start();
[email protected]255620da2013-08-19 13:14:294114 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304115 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4116 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354117 EXPECT_EQ(0, network_delegate.completed_requests());
4118 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194119 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354120 // Ensure that network delegate is notified.
4121 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194122 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4123 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354124 EXPECT_EQ(1, network_delegate.created_requests());
4125 EXPECT_EQ(0, network_delegate.destroyed_requests());
4126 }
4127 EXPECT_EQ(1, network_delegate.destroyed_requests());
4128}
4129
4130// Tests that we can handle when a network request was canceled while we were
4131// waiting for the network delegate.
4132// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
4133TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554134 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354135
4136 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304137 BlockingNetworkDelegate network_delegate(
4138 BlockingNetworkDelegate::USER_CALLBACK);
4139 network_delegate.set_block_on(
4140 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354141
[email protected]ef2bf422012-05-11 03:27:094142 TestURLRequestContext context(true);
4143 context.set_network_delegate(&network_delegate);
4144 context.Init();
[email protected]9045b8822012-01-13 20:35:354145
4146 {
[email protected]f7022f32014-08-21 16:32:194147 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554148 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354149
[email protected]f7022f32014-08-21 16:32:194150 r->Start();
[email protected]255620da2013-08-19 13:14:294151 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304152 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4153 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354154 EXPECT_EQ(0, network_delegate.completed_requests());
4155 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194156 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354157 // Ensure that network delegate is notified.
4158 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194159 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4160 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354161 EXPECT_EQ(1, network_delegate.created_requests());
4162 EXPECT_EQ(0, network_delegate.destroyed_requests());
4163 }
4164 EXPECT_EQ(1, network_delegate.destroyed_requests());
4165}
4166
4167// Tests that we can handle when a network request was canceled while we were
4168// waiting for the network delegate.
4169// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4170TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554171 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354172
4173 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304174 BlockingNetworkDelegate network_delegate(
4175 BlockingNetworkDelegate::USER_CALLBACK);
4176 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354177
[email protected]ef2bf422012-05-11 03:27:094178 TestURLRequestContext context(true);
4179 context.set_network_delegate(&network_delegate);
4180 context.Init();
[email protected]9045b8822012-01-13 20:35:354181
4182 {
[email protected]f7022f32014-08-21 16:32:194183 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554184 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354185
[email protected]f7022f32014-08-21 16:32:194186 r->Start();
[email protected]255620da2013-08-19 13:14:294187 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304188 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4189 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354190 EXPECT_EQ(0, network_delegate.completed_requests());
4191 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194192 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354193 // Ensure that network delegate is notified.
4194 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194195 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4196 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354197 EXPECT_EQ(1, network_delegate.created_requests());
4198 EXPECT_EQ(0, network_delegate.destroyed_requests());
4199 }
4200 EXPECT_EQ(1, network_delegate.destroyed_requests());
4201}
4202
4203// Tests that we can handle when a network request was canceled while we were
4204// waiting for the network delegate.
4205// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024206TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554207 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354208
4209 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304210 BlockingNetworkDelegate network_delegate(
4211 BlockingNetworkDelegate::USER_CALLBACK);
4212 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354213
[email protected]ef2bf422012-05-11 03:27:094214 TestURLRequestContext context(true);
4215 context.set_network_delegate(&network_delegate);
4216 context.Init();
[email protected]9045b8822012-01-13 20:35:354217
4218 {
[email protected]f7022f32014-08-21 16:32:194219 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554220 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354221
[email protected]f7022f32014-08-21 16:32:194222 r->Start();
[email protected]255620da2013-08-19 13:14:294223 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304224 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4225 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354226 EXPECT_EQ(0, network_delegate.completed_requests());
4227 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194228 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354229 // Ensure that network delegate is notified.
4230 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194231 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4232 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354233 EXPECT_EQ(1, network_delegate.created_requests());
4234 EXPECT_EQ(0, network_delegate.destroyed_requests());
4235 }
4236 EXPECT_EQ(1, network_delegate.destroyed_requests());
4237}
4238
tommycli59a63432015-11-06 00:10:554239namespace {
4240
4241scoped_ptr<test_server::HttpResponse> HandleServerAuthConnect(
4242 const test_server::HttpRequest& request) {
4243 if (request.headers.find("Host") == request.headers.end() ||
4244 request.headers.at("Host") != "www.server-auth.com" ||
4245 request.method != test_server::METHOD_CONNECT) {
4246 return nullptr;
4247 }
4248
4249 scoped_ptr<test_server::BasicHttpResponse> http_response(
4250 new test_server::BasicHttpResponse);
4251 http_response->set_code(HTTP_UNAUTHORIZED);
4252 http_response->AddCustomHeader("WWW-Authenticate",
4253 "Basic realm=\"WallyWorld\"");
4254 return http_response.Pass();
4255}
4256
4257} // namespace
4258
4259// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114260// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554261// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354262TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554263 http_test_server()->RegisterRequestHandler(
4264 base::Bind(&HandleServerAuthConnect));
4265 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114266
[email protected]ceefd7fd2012-11-29 00:36:244267 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044268 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554269 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504270
[email protected]dc651782009-02-14 01:45:084271 TestDelegate d;
4272 {
[email protected]f7022f32014-08-21 16:32:194273 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364274 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084275
[email protected]f7022f32014-08-21 16:32:194276 r->Start();
4277 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084278
[email protected]255620da2013-08-19 13:14:294279 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084280
[email protected]f7022f32014-08-21 16:32:194281 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:154282 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:194283 EXPECT_TRUE(r->proxy_server().IsEmpty());
4284 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:084285 }
4286}
4287
[email protected]b89290212009-08-14 22:37:354288TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554289 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114290
initial.commit586acc5fe2008-07-26 22:42:524291 TestDelegate d;
4292 {
[email protected]f7022f32014-08-21 16:32:194293 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554294 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524295
[email protected]f7022f32014-08-21 16:32:194296 r->Start();
4297 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524298
[email protected]255620da2013-08-19 13:14:294299 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524300
4301 EXPECT_EQ(1, d.response_started_count());
4302 EXPECT_FALSE(d.received_data_before_response());
4303 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554304 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194305 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554306 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194307 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164308
[email protected]9e743cd2010-03-16 07:03:534309 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524310 }
initial.commit586acc5fe2008-07-26 22:42:524311}
4312
[email protected]263163f2012-06-14 22:40:344313// This test has the server send a large number of cookies to the client.
4314// To ensure that no number of cookies causes a crash, a galloping binary
4315// search is used to estimate that maximum number of cookies that are accepted
4316// by the browser. Beyond the maximum number, the request will fail with
4317// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304318#if defined(OS_WIN)
4319// http://crbug.com/177916
4320#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4321#else
4322#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4323#endif // defined(OS_WIN)
4324TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554325 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344326
4327 int lower_bound = 0;
4328 int upper_bound = 1;
4329
4330 // Double the number of cookies until the response header limits are
4331 // exceeded.
4332 while (DoManyCookiesRequest(upper_bound)) {
4333 lower_bound = upper_bound;
4334 upper_bound *= 2;
4335 ASSERT_LT(upper_bound, 1000000);
4336 }
4337
pkasting6b68a162014-12-01 22:10:294338 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344339 if (tolerance < 2)
4340 tolerance = 2;
4341
4342 // Perform a binary search to find the highest possible number of cookies,
4343 // within the desired tolerance.
4344 while (upper_bound - lower_bound >= tolerance) {
4345 int num_cookies = (lower_bound + upper_bound) / 2;
4346
4347 if (DoManyCookiesRequest(num_cookies))
4348 lower_bound = num_cookies;
4349 else
4350 upper_bound = num_cookies;
4351 }
4352 // Success: the test did not crash.
4353}
4354
[email protected]b89290212009-08-14 22:37:354355TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554356 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114357
initial.commit586acc5fe2008-07-26 22:42:524358 TestDelegate d;
4359 {
[email protected]f7022f32014-08-21 16:32:194360 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554361 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524362
[email protected]f7022f32014-08-21 16:32:194363 r->Start();
4364 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524365
[email protected]255620da2013-08-19 13:14:294366 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524367
4368 EXPECT_EQ(1, d.response_started_count());
4369 EXPECT_FALSE(d.received_data_before_response());
4370 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554371 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194372 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554373 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194374 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524375 }
[email protected]5d7b373e2009-09-02 07:19:034376}
4377
[email protected]79e1fd62013-06-20 06:50:044378TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554379 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044380
4381 TestDelegate d;
4382 {
tommycli59a63432015-11-06 00:10:554383 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:364384 scoped_ptr<URLRequest> r(
4385 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044386
4387 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194388 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044389
[email protected]f7022f32014-08-21 16:32:194390 r->Start();
4391 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044392
[email protected]255620da2013-08-19 13:14:294393 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044394
4395 EXPECT_EQ(1, d.response_started_count());
4396 EXPECT_FALSE(d.received_data_before_response());
4397 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554398 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194399 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554400 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194401 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044402
4403 EXPECT_TRUE(d.have_full_request_headers());
4404 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4405 }
4406}
4407
[email protected]58e32bb2013-01-21 18:23:254408TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554409 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254410
4411 TestDelegate d;
4412 {
[email protected]f7022f32014-08-21 16:32:194413 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554414 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254415
[email protected]f7022f32014-08-21 16:32:194416 r->Start();
4417 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254418
[email protected]255620da2013-08-19 13:14:294419 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254420
4421 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194422 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254423 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4424
4425 EXPECT_EQ(1, d.response_started_count());
4426 EXPECT_FALSE(d.received_data_before_response());
4427 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554428 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194429 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554430 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194431 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254432 }
4433}
4434
tommycli59a63432015-11-06 00:10:554435// TODO(svaldez): Update tests to use EmbeddedTestServer.
4436#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394437TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:554438 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
4439 SpawnedTestServer::kLocalhost,
4440 base::FilePath(kTestFilePath));
4441
4442 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:394443
4444 // Parameter that specifies the Content-Length field in the response:
4445 // C - Compressed length.
4446 // U - Uncompressed length.
4447 // L - Large length (larger than both C & U).
4448 // M - Medium length (between C & U).
4449 // S - Small length (smaller than both C & U).
4450 const char test_parameters[] = "CULMS";
4451 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4452 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444453 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394454 // S has too little data, but we seem to accept it.
4455 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374456 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394457
4458 for (int i = 0; i < num_tests ; i++) {
4459 TestDelegate d;
4460 {
tommycli59a63432015-11-06 00:10:554461 std::string test_file = base::StringPrintf(
4462 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394463
[email protected]ceefd7fd2012-11-29 00:36:244464 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094465 TestURLRequestContext context(true);
4466 context.set_network_delegate(&network_delegate);
4467 context.Init();
[email protected]87a09a92011-07-14 15:50:504468
[email protected]f7022f32014-08-21 16:32:194469 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554470 test_server.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194471 r->Start();
4472 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394473
[email protected]255620da2013-08-19 13:14:294474 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394475
4476 EXPECT_EQ(1, d.response_started_count());
4477 EXPECT_FALSE(d.received_data_before_response());
4478 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194479 << " status = " << r->status().status()
4480 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394481 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194482 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394483 << " Parameter = \"" << test_file << "\"";
4484 } else {
[email protected]f7022f32014-08-21 16:32:194485 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4486 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394487 << " Parameter = \"" << test_file << "\"";
4488 }
4489 }
4490 }
4491}
tommycli59a63432015-11-06 00:10:554492#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394493
tbansala1caf9612015-06-01 20:24:184494TEST_F(URLRequestTestHTTP, NetworkQualityEstimator) {
tommycli59a63432015-11-06 00:10:554495 ASSERT_TRUE(http_test_server()->Start());
tbansalea2fb8c2015-05-22 22:23:004496 // Enable requests to local host to be used for network quality estimation.
tbansalb177b5392015-06-25 11:13:024497 std::map<std::string, std::string> variation_params;
tbansal1c92d5b2015-08-14 20:14:434498 NetworkQualityEstimator estimator(scoped_ptr<net::ExternalEstimateProvider>(),
4499 variation_params, true, true);
tbansalea2fb8c2015-05-22 22:23:004500
4501 TestDelegate d;
4502 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4503 TestURLRequestContext context(true);
4504 context.set_network_quality_estimator(&estimator);
4505 context.set_network_delegate(&network_delegate);
4506 context.Init();
4507
tommycli59a63432015-11-06 00:10:554508 std::string url = "/defaultresponse";
tbansalea2fb8c2015-05-22 22:23:004509
tommycli59a63432015-11-06 00:10:554510 scoped_ptr<URLRequest> r(context.CreateRequest(
4511 http_test_server()->GetURL(url), DEFAULT_PRIORITY, &d));
tbansalea2fb8c2015-05-22 22:23:004512 r->Start();
4513
4514 base::RunLoop().Run();
4515
tbansal9533b6f2015-08-11 22:06:084516 base::TimeDelta rtt;
4517 int32_t kbps;
4518 EXPECT_TRUE(estimator.GetRTTEstimate(&rtt));
4519 EXPECT_TRUE(estimator.GetDownlinkThroughputKbpsEstimate(&kbps));
4520 EXPECT_GE(rtt, base::TimeDelta());
4521 EXPECT_LT(rtt, base::TimeDelta::Max());
4522 EXPECT_GT(kbps, 0);
tbansalea2fb8c2015-05-22 22:23:004523
4524 // Verify that histograms are not populated. They should populate only when
4525 // there is a change in ConnectionType.
4526 base::HistogramTester histogram_tester;
4527 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 0);
4528 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 0);
4529
4530 NetworkChangeNotifier::NotifyObserversOfConnectionTypeChangeForTests(
4531 NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI);
4532 base::MessageLoop::current()->RunUntilIdle();
4533 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 1);
4534 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 1);
4535}
4536
[email protected]58e32bb2013-01-21 18:23:254537TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:554538 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254539
tommycli59a63432015-11-06 00:10:554540 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454541 GURL original_url =
tommycli59a63432015-11-06 00:10:554542 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254543 TestDelegate d;
davidben151423e2015-03-23 18:48:364544 scoped_ptr<URLRequest> req(
4545 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194546 req->Start();
[email protected]255620da2013-08-19 13:14:294547 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254548
4549 EXPECT_EQ(1, d.response_started_count());
4550 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194551 EXPECT_EQ(destination_url, req->url());
4552 EXPECT_EQ(original_url, req->original_url());
4553 ASSERT_EQ(2U, req->url_chain().size());
4554 EXPECT_EQ(original_url, req->url_chain()[0]);
4555 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254556
4557 LoadTimingInfo load_timing_info_before_redirect;
4558 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4559 &load_timing_info_before_redirect));
4560 TestLoadTimingNotReused(load_timing_info_before_redirect,
4561 CONNECT_TIMING_HAS_DNS_TIMES);
4562
4563 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194564 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254565 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4566
4567 // Check that a new socket was used on redirect, since the server does not
4568 // supposed keep-alive sockets, and that the times before the redirect are
4569 // before the ones recorded for the second request.
4570 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4571 load_timing_info.socket_log_id);
4572 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4573 load_timing_info.connect_timing.connect_start);
4574}
4575
[email protected]8f1ac082011-04-19 21:14:134576TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:554577 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:134578
tommycli59a63432015-11-06 00:10:554579 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454580 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:554581 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
4582 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
4583 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:134584 TestDelegate d;
davidben151423e2015-03-23 18:48:364585 scoped_ptr<URLRequest> req(
4586 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194587 req->Start();
[email protected]255620da2013-08-19 13:14:294588 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134589
4590 EXPECT_EQ(1, d.response_started_count());
4591 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194592 EXPECT_EQ(destination_url, req->url());
4593 EXPECT_EQ(original_url, req->original_url());
4594 ASSERT_EQ(3U, req->url_chain().size());
4595 EXPECT_EQ(original_url, req->url_chain()[0]);
4596 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4597 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134598}
4599
[email protected]abe1c4a2013-10-25 19:28:514600// First and second pieces of information logged by delegates to URLRequests.
4601const char kFirstDelegateInfo[] = "Wonderful delegate";
4602const char kSecondDelegateInfo[] = "Exciting delegate";
4603
4604// Logs delegate information to a URLRequest. The first string is logged
4605// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4606// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4607// another asynchronous call is used to clear the delegate information
4608// before calling a callback. The object then deletes itself.
4609class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4610 public:
4611 typedef base::Callback<void()> Callback;
4612
4613 // Each time delegate information is added to the URLRequest, the resulting
4614 // load state is checked. The expected load state after each request is
4615 // passed in as an argument.
4616 static void Run(URLRequest* url_request,
4617 LoadState expected_first_load_state,
4618 LoadState expected_second_load_state,
4619 LoadState expected_third_load_state,
4620 const Callback& callback) {
4621 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4622 url_request,
4623 expected_first_load_state,
4624 expected_second_load_state,
4625 expected_third_load_state,
4626 callback);
4627 logger->Start();
4628 }
4629
4630 // Checks that the log entries, starting with log_position, contain the
4631 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4632 // recorded. Returns the index of entry after the expected number of
4633 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464634 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514635 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514636 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4637 if (log_position + 3 >= entries.size()) {
4638 ADD_FAILURE() << "Not enough log entries";
4639 return entries.size();
4640 }
4641 std::string delegate_info;
4642 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4643 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4644 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4645 &delegate_info));
4646 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4647
4648 ++log_position;
4649 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4650 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4651
4652 ++log_position;
4653 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4654 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4655 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4656 &delegate_info));
4657 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4658
4659 ++log_position;
4660 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4661 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4662
4663 return log_position + 1;
4664 }
4665
[email protected]1826a402014-01-08 15:40:484666 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4667 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464668 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4669 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484670 log_position =
4671 ExpectLogContainsSomewhereAfter(entries,
4672 log_position,
4673 NetLog::TYPE_URL_REQUEST_DELEGATE,
4674 NetLog::PHASE_BEGIN);
4675 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4676 entries[log_position + 1].type);
4677 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4678 return log_position + 1;
4679 }
4680
[email protected]abe1c4a2013-10-25 19:28:514681 private:
4682 friend class base::RefCounted<AsyncDelegateLogger>;
4683
4684 AsyncDelegateLogger(URLRequest* url_request,
4685 LoadState expected_first_load_state,
4686 LoadState expected_second_load_state,
4687 LoadState expected_third_load_state,
4688 const Callback& callback)
4689 : url_request_(url_request),
4690 expected_first_load_state_(expected_first_load_state),
4691 expected_second_load_state_(expected_second_load_state),
4692 expected_third_load_state_(expected_third_load_state),
4693 callback_(callback) {
4694 }
4695
4696 ~AsyncDelegateLogger() {}
4697
4698 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534699 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514700 LoadStateWithParam load_state = url_request_->GetLoadState();
4701 EXPECT_EQ(expected_first_load_state_, load_state.state);
4702 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454703 base::ThreadTaskRunnerHandle::Get()->PostTask(
4704 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514705 }
4706
4707 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534708 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514709 LoadStateWithParam load_state = url_request_->GetLoadState();
4710 EXPECT_EQ(expected_second_load_state_, load_state.state);
4711 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4712 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4713 } else {
4714 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4715 }
skyostil4891b25b2015-06-11 11:43:454716 base::ThreadTaskRunnerHandle::Get()->PostTask(
4717 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514718 }
4719
4720 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534721 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514722 LoadStateWithParam load_state = url_request_->GetLoadState();
4723 EXPECT_EQ(expected_third_load_state_, load_state.state);
4724 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084725 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514726 callback_.Run();
4727 }
4728
4729 URLRequest* url_request_;
4730 const int expected_first_load_state_;
4731 const int expected_second_load_state_;
4732 const int expected_third_load_state_;
4733 const Callback callback_;
4734
4735 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4736};
4737
4738// NetworkDelegate that logs delegate information before a request is started,
4739// before headers are sent, when headers are read, and when auth information
4740// is requested. Uses AsyncDelegateLogger.
4741class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4742 public:
4743 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204744 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514745
4746 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204747 int OnBeforeURLRequest(URLRequest* request,
4748 const CompletionCallback& callback,
4749 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514750 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4751 return RunCallbackAsynchronously(request, callback);
4752 }
4753
dchengb03027d2014-10-21 12:00:204754 int OnBeforeSendHeaders(URLRequest* request,
4755 const CompletionCallback& callback,
4756 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514757 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4758 return RunCallbackAsynchronously(request, callback);
4759 }
4760
dchengb03027d2014-10-21 12:00:204761 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514762 URLRequest* request,
4763 const CompletionCallback& callback,
4764 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164765 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134766 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164767 TestNetworkDelegate::OnHeadersReceived(request,
4768 callback,
[email protected]abe1c4a2013-10-25 19:28:514769 original_response_headers,
[email protected]5f714132014-03-26 10:41:164770 override_response_headers,
4771 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514772 return RunCallbackAsynchronously(request, callback);
4773 }
4774
dchengb03027d2014-10-21 12:00:204775 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514776 URLRequest* request,
4777 const AuthChallengeInfo& auth_info,
4778 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134779 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514780 AsyncDelegateLogger::Run(
4781 request,
4782 LOAD_STATE_WAITING_FOR_DELEGATE,
4783 LOAD_STATE_WAITING_FOR_DELEGATE,
4784 LOAD_STATE_WAITING_FOR_DELEGATE,
4785 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4786 callback, credentials));
4787 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4788 }
4789
4790 private:
4791 static int RunCallbackAsynchronously(
4792 URLRequest* request,
4793 const CompletionCallback& callback) {
4794 AsyncDelegateLogger::Run(
4795 request,
4796 LOAD_STATE_WAITING_FOR_DELEGATE,
4797 LOAD_STATE_WAITING_FOR_DELEGATE,
4798 LOAD_STATE_WAITING_FOR_DELEGATE,
4799 base::Bind(callback, OK));
4800 return ERR_IO_PENDING;
4801 }
4802
4803 static void SetAuthAndResume(const AuthCallback& callback,
4804 AuthCredentials* credentials) {
4805 *credentials = AuthCredentials(kUser, kSecret);
4806 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4807 }
4808
4809 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4810};
4811
4812// URLRequest::Delegate that logs delegate information when the headers
4813// are received, when each read completes, and during redirects. Uses
4814// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4815//
4816// Inherits from TestDelegate to reuse the TestDelegate code to handle
4817// advancing to the next step in most cases, as well as cancellation.
4818class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4819 public:
4820 enum CancelStage {
4821 NO_CANCEL = 0,
4822 CANCEL_ON_RECEIVED_REDIRECT,
4823 CANCEL_ON_RESPONSE_STARTED,
4824 CANCEL_ON_READ_COMPLETED
4825 };
4826
4827 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4828 : cancel_stage_(cancel_stage) {
4829 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4830 set_cancel_in_received_redirect(true);
4831 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4832 set_cancel_in_response_started(true);
4833 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4834 set_cancel_in_received_data(true);
4835 }
dchengb03027d2014-10-21 12:00:204836 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514837
4838 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204839 void OnReceivedRedirect(URLRequest* request,
4840 const RedirectInfo& redirect_info,
4841 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514842 *defer_redirect = true;
4843 AsyncDelegateLogger::Run(
4844 request,
4845 LOAD_STATE_WAITING_FOR_DELEGATE,
4846 LOAD_STATE_WAITING_FOR_DELEGATE,
4847 LOAD_STATE_WAITING_FOR_DELEGATE,
4848 base::Bind(
4849 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594850 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514851 }
4852
dchengb03027d2014-10-21 12:00:204853 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514854 AsyncDelegateLogger::Run(
4855 request,
4856 LOAD_STATE_WAITING_FOR_DELEGATE,
4857 LOAD_STATE_WAITING_FOR_DELEGATE,
4858 LOAD_STATE_WAITING_FOR_DELEGATE,
4859 base::Bind(
4860 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4861 base::Unretained(this), request));
4862 }
4863
dchengb03027d2014-10-21 12:00:204864 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514865 AsyncDelegateLogger::Run(
4866 request,
4867 LOAD_STATE_IDLE,
4868 LOAD_STATE_IDLE,
4869 LOAD_STATE_IDLE,
4870 base::Bind(
4871 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4872 base::Unretained(this), request, bytes_read));
4873 }
4874
4875 private:
4876 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594877 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514878 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594879 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514880 // FollowDeferredRedirect should not be called after cancellation.
4881 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4882 return;
4883 if (!defer_redirect)
4884 request->FollowDeferredRedirect();
4885 }
4886
4887 void OnResponseStartedLoggingComplete(URLRequest* request) {
4888 // The parent class continues the request.
4889 TestDelegate::OnResponseStarted(request);
4890 }
4891
4892 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4893 // The parent class continues the request.
4894 TestDelegate::OnReadCompleted(request, bytes_read);
4895 }
4896
4897 const CancelStage cancel_stage_;
4898
4899 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4900};
4901
4902// Tests handling of delegate info before a request starts.
4903TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:554904 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:514905
4906 TestDelegate request_delegate;
4907 TestURLRequestContext context(true);
4908 context.set_network_delegate(NULL);
4909 context.set_net_log(&net_log_);
4910 context.Init();
4911
4912 {
davidben151423e2015-03-23 18:48:364913 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:554914 context.CreateRequest(http_test_server()->GetURL("/defaultresponse"),
davidben151423e2015-03-23 18:48:364915 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194916 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514917 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084918 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514919
4920 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194921 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514922 LOAD_STATE_WAITING_FOR_DELEGATE,
4923 LOAD_STATE_WAITING_FOR_DELEGATE,
4924 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194925 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514926
4927 base::RunLoop().Run();
4928
[email protected]f7022f32014-08-21 16:32:194929 EXPECT_EQ(200, r->GetResponseCode());
4930 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514931 }
4932
mmenke43758e62015-05-04 21:09:464933 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514934 net_log_.GetEntries(&entries);
4935 size_t log_position = ExpectLogContainsSomewhereAfter(
4936 entries,
4937 0,
4938 NetLog::TYPE_DELEGATE_INFO,
4939 NetLog::PHASE_BEGIN);
4940
4941 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4942
4943 // Nothing else should add any delegate info to the request.
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.
4949TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:554950 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:514951
4952 TestDelegate request_delegate;
4953 AsyncLoggingNetworkDelegate network_delegate;
4954 TestURLRequestContext context(true);
4955 context.set_network_delegate(&network_delegate);
4956 context.set_net_log(&net_log_);
4957 context.Init();
4958
4959 {
davidben151423e2015-03-23 18:48:364960 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:554961 context.CreateRequest(http_test_server()->GetURL("/simple.html"),
davidben151423e2015-03-23 18:48:364962 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194963 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514964 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084965 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514966
[email protected]f7022f32014-08-21 16:32:194967 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514968 base::RunLoop().Run();
4969
[email protected]f7022f32014-08-21 16:32:194970 EXPECT_EQ(200, r->GetResponseCode());
4971 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514972 EXPECT_EQ(1, network_delegate.created_requests());
4973 EXPECT_EQ(0, network_delegate.destroyed_requests());
4974 }
4975 EXPECT_EQ(1, network_delegate.destroyed_requests());
4976
4977 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464978 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514979 net_log_.GetEntries(&entries);
4980 for (size_t i = 0; i < 3; ++i) {
4981 log_position = ExpectLogContainsSomewhereAfter(
4982 entries,
4983 log_position + 1,
4984 NetLog::TYPE_URL_REQUEST_DELEGATE,
4985 NetLog::PHASE_BEGIN);
4986
4987 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4988 log_position + 1);
4989
4990 ASSERT_LT(log_position, entries.size());
4991 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4992 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484993
4994 if (i == 1) {
4995 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4996 entries, log_position + 1);
4997 }
[email protected]abe1c4a2013-10-25 19:28:514998 }
4999
5000 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5001 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5002}
5003
5004// Tests handling of delegate info from a network delegate in the case of an
5005// HTTP redirect.
5006TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555007 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515008
5009 TestDelegate request_delegate;
5010 AsyncLoggingNetworkDelegate network_delegate;
5011 TestURLRequestContext context(true);
5012 context.set_network_delegate(&network_delegate);
5013 context.set_net_log(&net_log_);
5014 context.Init();
5015
5016 {
[email protected]f7022f32014-08-21 16:32:195017 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555018 http_test_server()->GetURL("/server-redirect?simple.html"),
5019 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195020 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515021 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085022 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515023
[email protected]f7022f32014-08-21 16:32:195024 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515025 base::RunLoop().Run();
5026
[email protected]f7022f32014-08-21 16:32:195027 EXPECT_EQ(200, r->GetResponseCode());
5028 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515029 EXPECT_EQ(2, network_delegate.created_requests());
5030 EXPECT_EQ(0, network_delegate.destroyed_requests());
5031 }
5032 EXPECT_EQ(1, network_delegate.destroyed_requests());
5033
5034 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465035 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515036 net_log_.GetEntries(&entries);
5037 // The NetworkDelegate logged information in OnBeforeURLRequest,
5038 // OnBeforeSendHeaders, and OnHeadersReceived.
5039 for (size_t i = 0; i < 3; ++i) {
5040 log_position = ExpectLogContainsSomewhereAfter(
5041 entries,
5042 log_position + 1,
5043 NetLog::TYPE_URL_REQUEST_DELEGATE,
5044 NetLog::PHASE_BEGIN);
5045
5046 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5047 log_position + 1);
5048
5049 ASSERT_LT(log_position, entries.size());
5050 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5051 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485052
5053 if (i == 1) {
5054 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5055 entries, log_position + 1);
5056 }
[email protected]abe1c4a2013-10-25 19:28:515057 }
5058
5059 // The URLRequest::Delegate then gets informed about the redirect.
5060 log_position = ExpectLogContainsSomewhereAfter(
5061 entries,
5062 log_position + 1,
5063 NetLog::TYPE_URL_REQUEST_DELEGATE,
5064 NetLog::PHASE_BEGIN);
5065
5066 // The NetworkDelegate logged information in the same three events as before.
5067 for (size_t i = 0; i < 3; ++i) {
5068 log_position = ExpectLogContainsSomewhereAfter(
5069 entries,
5070 log_position + 1,
5071 NetLog::TYPE_URL_REQUEST_DELEGATE,
5072 NetLog::PHASE_BEGIN);
5073
5074 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5075 log_position + 1);
5076
5077 ASSERT_LT(log_position, entries.size());
5078 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5079 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5080 }
5081
5082 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5083 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5084}
5085
5086// Tests handling of delegate info from a network delegate in the case of HTTP
5087// AUTH.
5088TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555089 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515090
5091 TestDelegate request_delegate;
5092 AsyncLoggingNetworkDelegate network_delegate;
5093 TestURLRequestContext context(true);
5094 context.set_network_delegate(&network_delegate);
5095 context.set_net_log(&net_log_);
5096 context.Init();
5097
5098 {
davidben151423e2015-03-23 18:48:365099 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555100 context.CreateRequest(http_test_server()->GetURL("/auth-basic"),
davidben151423e2015-03-23 18:48:365101 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195102 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515103 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085104 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515105
[email protected]f7022f32014-08-21 16:32:195106 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515107 base::RunLoop().Run();
5108
[email protected]f7022f32014-08-21 16:32:195109 EXPECT_EQ(200, r->GetResponseCode());
5110 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515111 EXPECT_EQ(1, network_delegate.created_requests());
5112 EXPECT_EQ(0, network_delegate.destroyed_requests());
5113 }
5114 EXPECT_EQ(1, network_delegate.destroyed_requests());
5115
5116 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465117 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515118 net_log_.GetEntries(&entries);
5119 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
5120 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
5121 // OnBeforeURLRequest and OnBeforeSendHeaders.
5122 for (size_t i = 0; i < 6; ++i) {
5123 log_position = ExpectLogContainsSomewhereAfter(
5124 entries,
5125 log_position + 1,
5126 NetLog::TYPE_URL_REQUEST_DELEGATE,
5127 NetLog::PHASE_BEGIN);
5128
5129 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5130 log_position + 1);
5131
5132 ASSERT_LT(log_position, entries.size());
5133 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5134 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485135
5136 if (i == 1) {
5137 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5138 entries, log_position + 1);
5139 }
[email protected]abe1c4a2013-10-25 19:28:515140 }
5141
5142 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5143 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5144}
5145
tommycli59a63432015-11-06 00:10:555146// TODO(svaldez): Update tests to use EmbeddedTestServer.
5147#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515148// Tests handling of delegate info from a URLRequest::Delegate.
5149TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555150 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
5151 SpawnedTestServer::kLocalhost,
5152 base::FilePath(kTestFilePath));
5153
5154 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515155
5156 AsyncLoggingUrlRequestDelegate request_delegate(
5157 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5158 TestURLRequestContext context(true);
5159 context.set_network_delegate(NULL);
5160 context.set_net_log(&net_log_);
5161 context.Init();
5162
5163 {
5164 // A chunked response with delays between chunks is used to make sure that
5165 // attempts by the URLRequest delegate to log information while reading the
5166 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485167 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515168 // that it occurs.
[email protected]f7022f32014-08-21 16:32:195169 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555170 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365171 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195172 LoadStateWithParam load_state = r->GetLoadState();
5173 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515174 base::RunLoop().Run();
5175
[email protected]f7022f32014-08-21 16:32:195176 EXPECT_EQ(200, r->GetResponseCode());
5177 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515178 }
5179
mmenke43758e62015-05-04 21:09:465180 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515181 net_log_.GetEntries(&entries);
5182
[email protected]1826a402014-01-08 15:40:485183 size_t log_position = 0;
5184
5185 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5186 entries, log_position);
5187
[email protected]abe1c4a2013-10-25 19:28:515188 // The delegate info should only have been logged on header complete. Other
5189 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:485190 log_position =
5191 ExpectLogContainsSomewhereAfter(entries,
5192 log_position + 1,
5193 NetLog::TYPE_URL_REQUEST_DELEGATE,
5194 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515195
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 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5204 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5205 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5206 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5207}
tommycli59a63432015-11-06 00:10:555208#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515209
5210// Tests handling of delegate info from a URLRequest::Delegate in the case of
5211// an HTTP redirect.
5212TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555213 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515214
5215 AsyncLoggingUrlRequestDelegate request_delegate(
5216 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5217 TestURLRequestContext context(true);
5218 context.set_network_delegate(NULL);
5219 context.set_net_log(&net_log_);
5220 context.Init();
5221
5222 {
[email protected]f7022f32014-08-21 16:32:195223 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555224 http_test_server()->GetURL("/server-redirect?simple.html"),
5225 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195226 LoadStateWithParam load_state = r->GetLoadState();
5227 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515228 base::RunLoop().Run();
5229
[email protected]f7022f32014-08-21 16:32:195230 EXPECT_EQ(200, r->GetResponseCode());
5231 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515232 }
5233
mmenke43758e62015-05-04 21:09:465234 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515235 net_log_.GetEntries(&entries);
5236
5237 // Delegate info should only have been logged in OnReceivedRedirect and
5238 // OnResponseStarted.
5239 size_t log_position = 0;
5240 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485241 if (i == 0) {
5242 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5243 entries, log_position) + 1;
5244 }
5245
[email protected]abe1c4a2013-10-25 19:28:515246 log_position = ExpectLogContainsSomewhereAfter(
5247 entries,
5248 log_position,
5249 NetLog::TYPE_URL_REQUEST_DELEGATE,
5250 NetLog::PHASE_BEGIN);
5251
5252 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5253 log_position + 1);
5254
5255 ASSERT_LT(log_position, entries.size());
5256 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5257 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5258 }
5259
5260 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5261 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5262 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5263 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5264}
5265
5266// Tests handling of delegate info from a URLRequest::Delegate in the case of
5267// an HTTP redirect, with cancellation at various points.
5268TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555269 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515270
5271 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5272 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5273 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5274 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5275 };
5276
5277 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5278 ++test_case) {
5279 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5280 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:515281 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:515282 context.set_network_delegate(NULL);
5283 context.set_net_log(&net_log);
5284 context.Init();
5285
5286 {
[email protected]f7022f32014-08-21 16:32:195287 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555288 http_test_server()->GetURL("/server-redirect?simple.html"),
5289 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195290 LoadStateWithParam load_state = r->GetLoadState();
5291 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515292 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195293 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515294 }
5295
mmenke43758e62015-05-04 21:09:465296 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515297 net_log.GetEntries(&entries);
5298
5299 // Delegate info is always logged in both OnReceivedRedirect and
5300 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5301 // OnResponseStarted delegate call is after cancellation, but logging is
5302 // still currently supported in that call.
5303 size_t log_position = 0;
5304 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485305 if (i == 0) {
5306 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5307 entries, log_position) + 1;
5308 }
5309
[email protected]abe1c4a2013-10-25 19:28:515310 log_position = ExpectLogContainsSomewhereAfter(
5311 entries,
5312 log_position,
5313 NetLog::TYPE_URL_REQUEST_DELEGATE,
5314 NetLog::PHASE_BEGIN);
5315
5316 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5317 log_position + 1);
5318
5319 ASSERT_LT(log_position, entries.size());
5320 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5321 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5322 }
5323
5324 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5325 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5326 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5327 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5328 }
5329}
5330
[email protected]847c0fa92012-11-06 16:37:425331namespace {
5332
5333const char kExtraHeader[] = "Allow-Snafu";
5334const char kExtraValue[] = "fubar";
5335
5336class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205337 void OnReceivedRedirect(URLRequest* request,
5338 const RedirectInfo& redirect_info,
5339 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595340 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425341 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5342 }
5343};
5344
5345} // namespace
5346
5347TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555348 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425349
tommycli59a63432015-11-06 00:10:555350 GURL destination_url =
5351 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5352 GURL original_url =
5353 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425354 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:365355 scoped_ptr<URLRequest> req(
5356 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195357 req->Start();
[email protected]255620da2013-08-19 13:14:295358 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425359
5360 std::string value;
[email protected]f7022f32014-08-21 16:32:195361 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425362 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5363 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195364 EXPECT_FALSE(req->is_pending());
5365 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425366 EXPECT_EQ(kExtraValue, d.data_received());
5367}
5368
[email protected]251a1b92012-11-13 11:01:095369namespace {
5370
5371const char kExtraHeaderToRemove[] = "To-Be-Removed";
5372
5373class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205374 void OnReceivedRedirect(URLRequest* request,
5375 const RedirectInfo& redirect_info,
5376 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595377 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095378 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5379 }
5380};
5381
5382} // namespace
5383
5384TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555385 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095386
tommycli59a63432015-11-06 00:10:555387 GURL destination_url = http_test_server()->GetURL(
5388 "/echoheader?" + std::string(kExtraHeaderToRemove));
5389 GURL original_url =
5390 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095391 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:365392 scoped_ptr<URLRequest> req(
5393 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195394 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5395 req->Start();
[email protected]255620da2013-08-19 13:14:295396 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095397
5398 std::string value;
[email protected]f7022f32014-08-21 16:32:195399 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095400 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195401 EXPECT_FALSE(req->is_pending());
5402 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095403 EXPECT_EQ("None", d.data_received());
5404}
5405
[email protected]316c1e5e2012-09-12 15:17:445406TEST_F(URLRequestTestHTTP, CancelTest) {
5407 TestDelegate d;
5408 {
[email protected]f7022f32014-08-21 16:32:195409 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365410 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445411
[email protected]f7022f32014-08-21 16:32:195412 r->Start();
5413 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445414
[email protected]f7022f32014-08-21 16:32:195415 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445416
[email protected]255620da2013-08-19 13:14:295417 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445418
5419 // We expect to receive OnResponseStarted even though the request has been
5420 // cancelled.
5421 EXPECT_EQ(1, d.response_started_count());
5422 EXPECT_EQ(0, d.bytes_received());
5423 EXPECT_FALSE(d.received_data_before_response());
5424 }
5425}
5426
5427TEST_F(URLRequestTestHTTP, CancelTest2) {
tommycli59a63432015-11-06 00:10:555428 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445429
5430 TestDelegate d;
5431 {
[email protected]f7022f32014-08-21 16:32:195432 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555433 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445434
5435 d.set_cancel_in_response_started(true);
5436
[email protected]f7022f32014-08-21 16:32:195437 r->Start();
5438 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445439
[email protected]255620da2013-08-19 13:14:295440 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445441
5442 EXPECT_EQ(1, d.response_started_count());
5443 EXPECT_EQ(0, d.bytes_received());
5444 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195445 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445446 }
5447}
5448
5449TEST_F(URLRequestTestHTTP, CancelTest3) {
tommycli59a63432015-11-06 00:10:555450 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445451
5452 TestDelegate d;
5453 {
[email protected]f7022f32014-08-21 16:32:195454 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555455 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445456
5457 d.set_cancel_in_received_data(true);
5458
[email protected]f7022f32014-08-21 16:32:195459 r->Start();
5460 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445461
[email protected]255620da2013-08-19 13:14:295462 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445463
5464 EXPECT_EQ(1, d.response_started_count());
5465 // There is no guarantee about how much data was received
5466 // before the cancel was issued. It could have been 0 bytes,
5467 // or it could have been all the bytes.
5468 // EXPECT_EQ(0, d.bytes_received());
5469 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195470 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445471 }
5472}
5473
5474TEST_F(URLRequestTestHTTP, CancelTest4) {
tommycli59a63432015-11-06 00:10:555475 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445476
5477 TestDelegate d;
5478 {
[email protected]f7022f32014-08-21 16:32:195479 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555480 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445481
[email protected]f7022f32014-08-21 16:32:195482 r->Start();
5483 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445484
5485 // The request will be implicitly canceled when it is destroyed. The
5486 // test delegate must not post a quit message when this happens because
5487 // this test doesn't actually have a message loop. The quit message would
5488 // get put on this thread's message queue and the next test would exit
5489 // early, causing problems.
5490 d.set_quit_on_complete(false);
5491 }
5492 // expect things to just cleanup properly.
5493
5494 // we won't actually get a received reponse here because we've never run the
5495 // message loop
5496 EXPECT_FALSE(d.received_data_before_response());
5497 EXPECT_EQ(0, d.bytes_received());
5498}
5499
5500TEST_F(URLRequestTestHTTP, CancelTest5) {
tommycli59a63432015-11-06 00:10:555501 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445502
5503 // populate cache
5504 {
5505 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195506 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555507 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195508 r->Start();
[email protected]255620da2013-08-19 13:14:295509 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195510 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445511 }
5512
5513 // cancel read from cache (see bug 990242)
5514 {
5515 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195516 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555517 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195518 r->Start();
5519 r->Cancel();
[email protected]255620da2013-08-19 13:14:295520 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445521
[email protected]f7022f32014-08-21 16:32:195522 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445523 EXPECT_EQ(1, d.response_started_count());
5524 EXPECT_EQ(0, d.bytes_received());
5525 EXPECT_FALSE(d.received_data_before_response());
5526 }
5527}
5528
5529TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:555530 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445531 HTTPUploadDataOperationTest("POST");
5532}
5533
5534TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:555535 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445536 HTTPUploadDataOperationTest("PUT");
5537}
5538
5539TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:555540 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445541
5542 TestDelegate d;
5543 {
[email protected]f7022f32014-08-21 16:32:195544 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555545 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195546 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445547
[email protected]f7022f32014-08-21 16:32:195548 r->Start();
5549 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445550
[email protected]255620da2013-08-19 13:14:295551 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445552
[email protected]329b68b2012-11-14 17:54:275553 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195554 << "request failed: " << r->status().status()
5555 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445556
5557 EXPECT_FALSE(d.received_data_before_response());
5558 EXPECT_TRUE(d.data_received().empty());
5559 }
5560}
5561
5562TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:555563 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445564
5565 TestDelegate d;
5566 {
[email protected]f7022f32014-08-21 16:32:195567 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555568 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195569 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445570
[email protected]6cdfd7f2013-02-08 20:40:155571 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445572 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025573 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445574
olli.raula6df48b2a2015-11-26 07:40:225575 std::vector<scoped_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445576
[email protected]6cdfd7f2013-02-08 20:40:155577 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445578 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475579 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445580 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
avibf0746c2015-12-09 19:53:145581 element_readers.push_back(make_scoped_ptr(new UploadFileElementReader(
5582 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
5583 std::numeric_limits<uint64_t>::max(), base::Time())));
mmenkecbc2b712014-10-09 20:29:075584 r->set_upload(make_scoped_ptr<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225585 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:445586
[email protected]f7022f32014-08-21 16:32:195587 r->Start();
5588 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445589
[email protected]255620da2013-08-19 13:14:295590 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445591
avibf0746c2015-12-09 19:53:145592 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:295593 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5594 ASSERT_LE(size64, std::numeric_limits<int>::max());
5595 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175596 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445597
[email protected]7600d0b2013-12-08 21:43:305598 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445599
[email protected]329b68b2012-11-14 17:54:275600 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195601 << "request failed: " << r->status().status()
5602 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445603
5604 EXPECT_FALSE(d.received_data_before_response());
5605
[email protected]329b68b2012-11-14 17:54:275606 EXPECT_EQ(size, d.bytes_received());
5607 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445608 }
5609}
5610
[email protected]999dd8c2013-11-12 06:45:545611TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:555612 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:545613
5614 TestDelegate d;
5615 {
[email protected]f7022f32014-08-21 16:32:195616 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555617 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195618 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545619
olli.raula6df48b2a2015-11-26 07:40:225620 std::vector<scoped_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:545621
olli.raula6df48b2a2015-11-26 07:40:225622 element_readers.push_back(make_scoped_ptr(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455623 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545624 base::FilePath(FILE_PATH_LITERAL(
5625 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
avibf0746c2015-12-09 19:53:145626 0, std::numeric_limits<uint64_t>::max(), base::Time())));
mmenkecbc2b712014-10-09 20:29:075627 r->set_upload(make_scoped_ptr<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225628 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:545629
[email protected]f7022f32014-08-21 16:32:195630 r->Start();
5631 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545632
5633 base::RunLoop().Run();
5634
[email protected]999dd8c2013-11-12 06:45:545635 EXPECT_TRUE(d.request_failed());
5636 EXPECT_FALSE(d.received_data_before_response());
5637 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195638 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5639 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545640 }
5641}
5642
[email protected]316c1e5e2012-09-12 15:17:445643TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:555644 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445645
5646 TestDelegate d;
5647 {
[email protected]f7022f32014-08-21 16:32:195648 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555649 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195650 r->EnableChunkedUpload();
5651 r->set_method("POST");
5652 AddChunksToUpload(r.get());
5653 r->Start();
5654 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445655
[email protected]255620da2013-08-19 13:14:295656 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445657
[email protected]f7022f32014-08-21 16:32:195658 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445659 }
5660}
5661
[email protected]329b68b2012-11-14 17:54:275662TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:555663 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:275664
5665 TestDelegate d;
5666 {
[email protected]f7022f32014-08-21 16:32:195667 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555668 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195669 r->EnableChunkedUpload();
5670 r->set_method("POST");
5671 r->Start();
5672 EXPECT_TRUE(r->is_pending());
5673 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295674 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275675
[email protected]f7022f32014-08-21 16:32:195676 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275677 }
5678}
5679
[email protected]316c1e5e2012-09-12 15:17:445680TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:555681 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445682
5683 TestDelegate d;
5684 {
[email protected]f7022f32014-08-21 16:32:195685 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555686 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195687 r->EnableChunkedUpload();
5688 r->set_method("POST");
5689 r->Start();
5690 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445691
[email protected]255620da2013-08-19 13:14:295692 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195693 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295694 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445695
[email protected]f7022f32014-08-21 16:32:195696 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445697 }
5698}
5699
5700TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:555701 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445702
5703 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195704 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555705 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195706 req->Start();
[email protected]255620da2013-08-19 13:14:295707 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445708
[email protected]f7022f32014-08-21 16:32:195709 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445710
5711 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195712 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445713
5714 std::string header;
5715 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5716 EXPECT_EQ("private", header);
5717
5718 header.clear();
5719 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5720 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5721
5722 // The response has two "X-Multiple-Entries" headers.
5723 // This verfies our output has them concatenated together.
5724 header.clear();
5725 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5726 EXPECT_EQ("a, b", header);
5727}
5728
tommycli59a63432015-11-06 00:10:555729// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
5730// security state. (see http://crbug.com/550977).
5731#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:465732TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:555733 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5734 https_test_server.SetSSLConfig(
5735 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5736 https_test_server.ServeFilesFromSourceDirectory(
5737 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465738 ASSERT_TRUE(https_test_server.Start());
5739
tommycli59a63432015-11-06 00:10:555740 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:465741 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195742 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555743 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195744 request->Start();
[email protected]255620da2013-08-19 13:14:295745 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465746
5747 TransportSecurityState* security_state =
5748 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405749 TransportSecurityState::STSState sts_state;
5750 TransportSecurityState::PKPState pkp_state;
5751 EXPECT_TRUE(
5752 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5753 EXPECT_FALSE(
5754 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5755 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5756 sts_state.upgrade_mode);
5757 EXPECT_TRUE(sts_state.include_subdomains);
5758 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:035759#if defined(OS_ANDROID)
5760 // Android's CertVerifyProc does not (yet) handle pins.
5761#else
martijnc0d6b622015-06-30 19:14:405762 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035763#endif
[email protected]37fd55fb2013-06-29 13:13:275764}
5765
estarka5da76702015-04-09 04:00:165766TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555767 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5768 https_test_server.ServeFilesFromSourceDirectory(
5769 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165770 ASSERT_TRUE(https_test_server.Start());
5771 // Make sure this test fails if the test server is changed to not
5772 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555773 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5774 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165775
5776 TestDelegate d;
5777 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555778 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:165779 request->Start();
5780 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:165781 TransportSecurityState* security_state =
5782 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405783 TransportSecurityState::STSState sts_state;
5784 EXPECT_FALSE(
5785 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165786}
5787
mathpc992e602015-10-21 20:34:035788// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5789// reject HPKP headers, and a test setting only HPKP headers will fail (no
5790// PKPState present because header rejected).
5791#if defined(OS_ANDROID)
5792#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5793#define MAYBE_ProcessPKPAndSendReport DISABLED_ProcessPKPAndSendReport
5794#define MAYBE_ProcessPKPReportOnly DISABLED_ProcessPKPReportOnly
5795#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5796 DISABLED_ProcessPKPReportOnlyWithNoViolation
5797#else
5798#define MAYBE_ProcessPKP ProcessPKP
5799#define MAYBE_ProcessPKPAndSendReport ProcessPKPAndSendReport
5800#define MAYBE_ProcessPKPReportOnly ProcessPKPReportOnly
5801#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5802 ProcessPKPReportOnlyWithNoViolation
5803#endif
5804
estark06e0dac2015-08-07 21:56:015805namespace {
5806const char kHPKPReportUri[] = "https://hpkp-report.test";
5807} // namespace
5808
[email protected]37fd55fb2013-06-29 13:13:275809// Tests that enabling HPKP on a domain does not affect the HSTS
5810// validity/expiration.
mathpc992e602015-10-21 20:34:035811TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estark06e0dac2015-08-07 21:56:015812 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555813 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5814 https_test_server.SetSSLConfig(
5815 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5816 https_test_server.ServeFilesFromSourceDirectory(
5817 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275818 ASSERT_TRUE(https_test_server.Start());
5819
tommycli59a63432015-11-06 00:10:555820 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165821
[email protected]37fd55fb2013-06-29 13:13:275822 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195823 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555824 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195825 request->Start();
[email protected]255620da2013-08-19 13:14:295826 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275827 TransportSecurityState* security_state =
5828 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405829 TransportSecurityState::STSState sts_state;
5830 TransportSecurityState::PKPState pkp_state;
5831 EXPECT_FALSE(
5832 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5833 EXPECT_TRUE(
5834 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5835 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
5836 sts_state.upgrade_mode);
5837 EXPECT_FALSE(sts_state.include_subdomains);
5838 EXPECT_FALSE(pkp_state.include_subdomains);
5839 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:015840 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:405841 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:465842}
5843
estark06e0dac2015-08-07 21:56:015844// Tests that reports get sent on HPKP violations when a report-uri is set.
mathpc992e602015-10-21 20:34:035845TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:015846 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555847 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5848 https_test_server.SetSSLConfig(
5849 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5850 https_test_server.ServeFilesFromSourceDirectory(
5851 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015852 ASSERT_TRUE(https_test_server.Start());
5853
tommycli59a63432015-11-06 00:10:555854 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015855
5856 // Set up a pin for |test_server_hostname|.
5857 TransportSecurityState security_state;
5858 const base::Time current_time(base::Time::Now());
5859 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
5860 HashValueVector hashes;
5861 HashValue hash1;
5862 HashValue hash2;
5863 // The values here don't matter, as long as they are different from
5864 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:445865 ASSERT_TRUE(
5866 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
5867 ASSERT_TRUE(
5868 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:015869 hashes.push_back(hash1);
5870 hashes.push_back(hash2);
5871 security_state.AddHPKP(test_server_hostname, expiry,
5872 false, /* include subdomains */
5873 hashes, report_uri);
5874
5875 MockCertificateReportSender mock_report_sender;
5876 security_state.SetReportSender(&mock_report_sender);
5877
5878 // Set up a MockCertVerifier to trigger a violation of the previously
5879 // set pin.
5880 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5881 ASSERT_TRUE(cert);
5882
5883 MockCertVerifier cert_verifier;
5884 CertVerifyResult verify_result;
5885 verify_result.verified_cert = cert;
5886 verify_result.is_issued_by_known_root = true;
5887 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:445888 ASSERT_TRUE(
5889 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:015890 verify_result.public_key_hashes.push_back(hash3);
5891 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5892
5893 TestNetworkDelegate network_delegate;
5894 TestURLRequestContext context(true);
5895 context.set_transport_security_state(&security_state);
5896 context.set_network_delegate(&network_delegate);
5897 context.set_cert_verifier(&cert_verifier);
5898 context.Init();
5899
5900 // Now send a request to trigger the violation.
5901 TestDelegate d;
5902 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555903 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
estark06e0dac2015-08-07 21:56:015904 violating_request->Start();
5905 base::RunLoop().Run();
5906
5907 // Check that a report was sent.
5908 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5909 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5910 scoped_ptr<base::Value> value(
5911 base::JSONReader::Read(mock_report_sender.latest_report()));
5912 ASSERT_TRUE(value);
5913 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
5914 base::DictionaryValue* report_dict;
5915 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
5916 std::string report_hostname;
5917 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
5918 EXPECT_EQ(test_server_hostname, report_hostname);
5919}
5920
5921// Tests that reports get sent on requests with
5922// Public-Key-Pins-Report-Only headers.
mathpc992e602015-10-21 20:34:035923TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:015924 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555925 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5926 https_test_server.SetSSLConfig(
5927 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5928 https_test_server.ServeFilesFromSourceDirectory(
5929 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015930 ASSERT_TRUE(https_test_server.Start());
5931
tommycli59a63432015-11-06 00:10:555932 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015933
5934 TransportSecurityState security_state;
5935 MockCertificateReportSender mock_report_sender;
5936 security_state.SetReportSender(&mock_report_sender);
5937
5938 // Set up a MockCertVerifier to violate the pin in the Report-Only
5939 // header.
5940 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5941 ASSERT_TRUE(cert);
5942
5943 MockCertVerifier cert_verifier;
5944 CertVerifyResult verify_result;
5945 verify_result.verified_cert = cert;
5946 verify_result.is_issued_by_known_root = true;
5947 HashValue hash;
5948 // This value doesn't matter, as long as it is different from the pins
5949 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:445950 ASSERT_TRUE(
5951 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:015952 verify_result.public_key_hashes.push_back(hash);
5953 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5954
5955 TestNetworkDelegate network_delegate;
5956 TestURLRequestContext context(true);
5957 context.set_transport_security_state(&security_state);
5958 context.set_network_delegate(&network_delegate);
5959 context.set_cert_verifier(&cert_verifier);
5960 context.Init();
5961
5962 // Now send a request to trigger the violation.
5963 TestDelegate d;
5964 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555965 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:015966 DEFAULT_PRIORITY, &d));
5967 violating_request->Start();
5968 base::RunLoop().Run();
5969
5970 // Check that a report was sent.
5971 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5972 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5973 scoped_ptr<base::Value> value(
5974 base::JSONReader::Read(mock_report_sender.latest_report()));
5975 ASSERT_TRUE(value);
5976 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
5977 base::DictionaryValue* report_dict;
5978 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
5979 std::string report_hostname;
5980 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
5981 EXPECT_EQ(test_server_hostname, report_hostname);
5982}
5983
5984// Tests that reports do not get sent on requests with
5985// Public-Key-Pins-Report-Only headers that don't have pin violations.
mathpc992e602015-10-21 20:34:035986TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:015987 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555988 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5989 https_test_server.SetSSLConfig(
5990 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5991 https_test_server.ServeFilesFromSourceDirectory(
5992 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015993 ASSERT_TRUE(https_test_server.Start());
5994
tommycli59a63432015-11-06 00:10:555995 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015996
5997 TransportSecurityState security_state;
5998 MockCertificateReportSender mock_report_sender;
5999 security_state.SetReportSender(&mock_report_sender);
6000
6001 TestNetworkDelegate network_delegate;
6002 MockCertVerifier mock_cert_verifier;
6003 TestURLRequestContext context(true);
6004 context.set_transport_security_state(&security_state);
6005 context.set_network_delegate(&network_delegate);
6006 context.set_cert_verifier(&mock_cert_verifier);
6007 mock_cert_verifier.set_default_result(OK);
6008 context.Init();
6009
6010 // Now send a request that does not trigger the violation.
6011 TestDelegate d;
6012 scoped_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556013 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016014 DEFAULT_PRIORITY, &d));
6015 request->Start();
6016 base::RunLoop().Run();
6017
6018 // Check that a report was not sent.
6019 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6020 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6021}
6022
estarka5da76702015-04-09 04:00:166023TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556024 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6025 https_test_server.ServeFilesFromSourceDirectory(
6026 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166027 ASSERT_TRUE(https_test_server.Start());
6028 // Make sure this test fails if the test server is changed to not
6029 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556030 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6031 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166032
6033 TestDelegate d;
6034 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556035 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:166036 request->Start();
6037 base::RunLoop().Run();
6038
6039 TransportSecurityState* security_state =
6040 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406041 TransportSecurityState::PKPState pkp_state;
6042 EXPECT_FALSE(
6043 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166044}
6045
[email protected]242d8562012-10-30 21:20:466046TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556047 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6048 https_test_server.SetSSLConfig(
6049 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6050 https_test_server.ServeFilesFromSourceDirectory(
6051 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466052 ASSERT_TRUE(https_test_server.Start());
6053
tommycli59a63432015-11-06 00:10:556054 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166055
[email protected]242d8562012-10-30 21:20:466056 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196057 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556058 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
6059 &d));
[email protected]f7022f32014-08-21 16:32:196060 request->Start();
[email protected]255620da2013-08-19 13:14:296061 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466062
6063 // We should have set parameters from the first header, not the second.
6064 TransportSecurityState* security_state =
6065 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406066 TransportSecurityState::STSState sts_state;
6067 EXPECT_TRUE(
6068 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6069 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6070 sts_state.upgrade_mode);
6071 EXPECT_FALSE(sts_state.include_subdomains);
6072 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466073}
6074
[email protected]9f972ec2013-04-10 20:24:366075TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556076 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6077 https_test_server.SetSSLConfig(
6078 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6079 https_test_server.ServeFilesFromSourceDirectory(
6080 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366081 ASSERT_TRUE(https_test_server.Start());
6082
tommycli59a63432015-11-06 00:10:556083 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166084
[email protected]9f972ec2013-04-10 20:24:366085 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196086 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556087 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
6088 &d));
[email protected]f7022f32014-08-21 16:32:196089 request->Start();
[email protected]255620da2013-08-19 13:14:296090 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366091
6092 // We should have set parameters from the first header, not the second.
6093 TransportSecurityState* security_state =
6094 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406095 TransportSecurityState::STSState sts_state;
6096 TransportSecurityState::PKPState pkp_state;
6097 EXPECT_TRUE(
6098 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6099 EXPECT_TRUE(
6100 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6101 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6102 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036103#if defined(OS_ANDROID)
6104 // Android's CertVerifyProc does not (yet) handle pins.
6105#else
martijnc0d6b622015-06-30 19:14:406106 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036107#endif
martijnc0d6b622015-06-30 19:14:406108 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366109
[email protected]a165f092013-06-12 16:10:056110 // Even though there is an HSTS header asserting includeSubdomains, it is
6111 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406112 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056113 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406114 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366115}
6116
[email protected]37fd55fb2013-06-29 13:13:276117// Tests that when multiple HPKP headers are present, asserting different
6118// policies, that only the first such policy is processed.
6119TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556120 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6121 https_test_server.SetSSLConfig(
6122 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6123 https_test_server.ServeFilesFromSourceDirectory(
6124 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276125 ASSERT_TRUE(https_test_server.Start());
6126
tommycli59a63432015-11-06 00:10:556127 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166128
[email protected]37fd55fb2013-06-29 13:13:276129 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196130 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556131 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:366132 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196133 request->Start();
[email protected]255620da2013-08-19 13:14:296134 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276135
6136 TransportSecurityState* security_state =
6137 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406138 TransportSecurityState::STSState sts_state;
6139 TransportSecurityState::PKPState pkp_state;
6140 EXPECT_TRUE(
6141 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6142 EXPECT_TRUE(
6143 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6144 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6145 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036146#if defined(OS_ANDROID)
6147 // Android's CertVerifyProc does not (yet) handle pins.
6148#else
martijnc0d6b622015-06-30 19:14:406149 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036150#endif
martijnc0d6b622015-06-30 19:14:406151 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276152
martijnc0d6b622015-06-30 19:14:406153 EXPECT_TRUE(sts_state.include_subdomains);
6154 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276155}
6156
tommycli59a63432015-11-06 00:10:556157#endif // !defined(OS_IOS)
6158
[email protected]316c1e5e2012-09-12 15:17:446159TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:556160 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446161
6162 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196163 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556164 http_test_server()->GetURL("/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366165 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196166 req->Start();
[email protected]255620da2013-08-19 13:14:296167 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446168
6169 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196170 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446171 EXPECT_EQ("text/html", mime_type);
6172
6173 std::string charset;
[email protected]f7022f32014-08-21 16:32:196174 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446175 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196176 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446177}
6178
[email protected]02494ec2014-05-07 15:05:296179TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346180 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346181 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346182 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026183 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346184
6185 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506186 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346187}
6188
[email protected]02494ec2014-05-07 15:05:296189#if !defined(DISABLE_FILE_SUPPORT)
6190TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6191 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6192 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456193 FileProtocolHandler file_protocol_handler(
6194 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296195 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6196
6197 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506198 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296199}
6200
[email protected]588614c22013-08-16 00:09:026201TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:556202 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446203
6204 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196205 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556206 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366207 &d));
[email protected]f7022f32014-08-21 16:32:196208 req->Start();
[email protected]255620da2013-08-19 13:14:296209 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446210
[email protected]f7022f32014-08-21 16:32:196211 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6212 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446213}
[email protected]02494ec2014-05-07 15:05:296214#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446215
[email protected]588614c22013-08-16 00:09:026216TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:556217 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:026218
6219 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196220 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556221 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366222 &d));
[email protected]f7022f32014-08-21 16:32:196223 req->Start();
[email protected]588614c22013-08-16 00:09:026224 base::MessageLoop::current()->Run();
6225
[email protected]f7022f32014-08-21 16:32:196226 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6227 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:026228}
6229
[email protected]316c1e5e2012-09-12 15:17:446230TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:556231 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446232
6233 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196234 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556235 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366236 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196237 req->Start();
[email protected]255620da2013-08-19 13:14:296238 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446239
[email protected]f7022f32014-08-21 16:32:196240 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6241 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446242}
6243
[email protected]e50efea2014-03-24 18:41:006244// Make sure redirects are cached, despite not reading their bodies.
6245TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:556246 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006247 GURL redirect_url =
tommycli59a63432015-11-06 00:10:556248 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:006249
6250 {
6251 TestDelegate d;
davidben151423e2015-03-23 18:48:366252 scoped_ptr<URLRequest> req(
6253 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196254 req->Start();
[email protected]e50efea2014-03-24 18:41:006255 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196256 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006257 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:556258 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006259 }
6260
6261 {
6262 TestDelegate d;
6263 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:366264 scoped_ptr<URLRequest> req(
6265 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196266 req->Start();
[email protected]e50efea2014-03-24 18:41:006267 base::RunLoop().Run();
6268
6269 EXPECT_EQ(1, d.received_redirect_count());
6270 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196271 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006272
[email protected]f7022f32014-08-21 16:32:196273 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006274 base::RunLoop().Run();
6275 EXPECT_EQ(1, d.received_redirect_count());
6276 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196277 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
tommycli59a63432015-11-06 00:10:556278 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006279 }
6280}
6281
6282// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6283// when the headers are read, since the body won't have been read.
6284TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:556285 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006286 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:556287 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:006288
6289 {
6290 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:556291 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:006292 default_network_delegate_.set_redirect_on_headers_received_url(
6293 redirect_to_url);
6294
6295 TestDelegate d;
davidben151423e2015-03-23 18:48:366296 scoped_ptr<URLRequest> req(
6297 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196298 req->Start();
[email protected]e50efea2014-03-24 18:41:006299 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196300 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006301 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196302 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006303 }
6304
6305 {
6306 TestDelegate d;
davidben151423e2015-03-23 18:48:366307 scoped_ptr<URLRequest> req(
6308 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196309 req->Start();
[email protected]e50efea2014-03-24 18:41:006310 base::RunLoop().Run();
6311
[email protected]f7022f32014-08-21 16:32:196312 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6313 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006314 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196315 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006316 }
6317}
6318
[email protected]5f714132014-03-26 10:41:166319// Tests that redirection to an unsafe URL is allowed when it has been marked as
6320// safe.
6321TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:556322 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166323
6324 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6325 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6326 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6327
6328 TestDelegate d;
6329 {
[email protected]f7022f32014-08-21 16:32:196330 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556331 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166332
[email protected]f7022f32014-08-21 16:32:196333 r->Start();
[email protected]5f714132014-03-26 10:41:166334 base::RunLoop().Run();
6335
[email protected]f7022f32014-08-21 16:32:196336 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:166337
[email protected]f7022f32014-08-21 16:32:196338 EXPECT_EQ(2U, r->url_chain().size());
6339 EXPECT_EQ(OK, r->status().error());
6340 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166341 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6342 }
6343}
6344
6345// Tests that a redirect to a different unsafe URL is blocked, even after adding
6346// some other URL to the whitelist.
6347TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:556348 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166349
6350 GURL unsafe_url("data:text/html,something");
6351 GURL different_unsafe_url("data:text/html,something-else");
6352 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6353 default_network_delegate_.set_allowed_unsafe_redirect_url(
6354 different_unsafe_url);
6355
6356 TestDelegate d;
6357 {
[email protected]f7022f32014-08-21 16:32:196358 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556359 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166360
[email protected]f7022f32014-08-21 16:32:196361 r->Start();
[email protected]5f714132014-03-26 10:41:166362 base::RunLoop().Run();
6363
[email protected]f7022f32014-08-21 16:32:196364 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
6365 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:166366 }
6367}
6368
[email protected]5f714132014-03-26 10:41:166369// Redirects from an URL with fragment to an unsafe URL with fragment should
6370// be allowed, and the reference fragment of the target URL should be preserved.
6371TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:556372 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166373
tommycli59a63432015-11-06 00:10:556374 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:166375 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6376 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6377
6378 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6379 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6380
6381 TestDelegate d;
6382 {
davidben151423e2015-03-23 18:48:366383 scoped_ptr<URLRequest> r(
6384 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166385
[email protected]f7022f32014-08-21 16:32:196386 r->Start();
[email protected]5f714132014-03-26 10:41:166387 base::RunLoop().Run();
6388
[email protected]f7022f32014-08-21 16:32:196389 EXPECT_EQ(2U, r->url_chain().size());
6390 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6391 EXPECT_EQ(OK, r->status().error());
6392 EXPECT_EQ(original_url, r->original_url());
6393 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166394 }
6395}
6396
6397// When a delegate has specified a safe redirect URL, but it does not match the
6398// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146399TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:556400 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166401
tommycli59a63432015-11-06 00:10:556402 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166403 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:556404 GURL redirect_url(http_test_server()->GetURL("/target"));
6405 GURL expected_redirect_url(
6406 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166407
6408 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6409 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6410
6411 TestDelegate d;
6412 {
davidben151423e2015-03-23 18:48:366413 scoped_ptr<URLRequest> r(
6414 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166415
[email protected]f7022f32014-08-21 16:32:196416 r->Start();
[email protected]5f714132014-03-26 10:41:166417 base::RunLoop().Run();
6418
[email protected]f7022f32014-08-21 16:32:196419 EXPECT_EQ(2U, r->url_chain().size());
6420 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6421 EXPECT_EQ(OK, r->status().error());
6422 EXPECT_EQ(original_url, r->original_url());
6423 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166424 }
6425}
6426
[email protected]f878230e2014-04-03 15:36:146427// When a delegate has specified a safe redirect URL, assume that the redirect
6428// URL should not be changed. In particular, the reference fragment should not
6429// be modified.
6430TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556431 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146432
tommycli59a63432015-11-06 00:10:556433 GURL original_url(
6434 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:146435 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6436
6437 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6438 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6439
6440 TestDelegate d;
6441 {
davidben151423e2015-03-23 18:48:366442 scoped_ptr<URLRequest> r(
6443 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146444
[email protected]f7022f32014-08-21 16:32:196445 r->Start();
[email protected]f878230e2014-04-03 15:36:146446 base::RunLoop().Run();
6447
[email protected]f7022f32014-08-21 16:32:196448 EXPECT_EQ(2U, r->url_chain().size());
6449 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6450 EXPECT_EQ(OK, r->status().error());
6451 EXPECT_EQ(original_url, r->original_url());
6452 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146453 }
6454}
6455
6456// When a URLRequestRedirectJob is created, the redirection must be followed and
6457// the reference fragment of the target URL must not be modified.
6458TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556459 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146460
tommycli59a63432015-11-06 00:10:556461 GURL original_url(
6462 http_test_server()->GetURL("/original#should-not-be-appended"));
6463 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:146464
6465 TestDelegate d;
davidben151423e2015-03-23 18:48:366466 scoped_ptr<URLRequest> r(
6467 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146468
mmenkeed0498b2015-12-08 23:20:426469 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196470 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:426471 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
6472 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:146473
[email protected]f7022f32014-08-21 16:32:196474 r->Start();
[email protected]f878230e2014-04-03 15:36:146475 base::RunLoop().Run();
6476
[email protected]f7022f32014-08-21 16:32:196477 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6478 EXPECT_EQ(OK, r->status().error());
6479 EXPECT_EQ(original_url, r->original_url());
6480 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146481}
6482
[email protected]316c1e5e2012-09-12 15:17:446483TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:556484 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446485
6486 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196487 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556488 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196489 req->SetReferrer("http://user:[email protected]/");
6490 req->Start();
[email protected]255620da2013-08-19 13:14:296491 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446492
6493 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6494}
6495
[email protected]99ecf6e2013-04-10 22:46:136496TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:556497 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136498
6499 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196500 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556501 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196502 req->SetReferrer("http://foo.com/test#fragment");
6503 req->Start();
[email protected]255620da2013-08-19 13:14:296504 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136505
6506 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6507}
6508
6509TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:556510 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136511
6512 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196513 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556514 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196515 req->SetReferrer("http://foo.com/test#fragment");
6516 req->SetReferrer("");
6517 req->Start();
[email protected]255620da2013-08-19 13:14:296518 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136519
6520 EXPECT_EQ(std::string("None"), d.data_received());
6521}
6522
[email protected]1826a402014-01-08 15:40:486523// Defer network start and then resume, checking that the request was a success
6524// and bytes were received.
6525TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556526 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486527
6528 TestDelegate d;
6529 {
6530 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556531 GURL test_url(http_test_server()->GetURL("/echo"));
davidben151423e2015-03-23 18:48:366532 scoped_ptr<URLRequest> req(
6533 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486534
[email protected]f7022f32014-08-21 16:32:196535 req->Start();
[email protected]1826a402014-01-08 15:40:486536 base::RunLoop().Run();
6537
6538 EXPECT_EQ(1, d.received_before_network_start_count());
6539 EXPECT_EQ(0, d.response_started_count());
6540
[email protected]f7022f32014-08-21 16:32:196541 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486542 base::RunLoop().Run();
6543
6544 EXPECT_EQ(1, d.response_started_count());
6545 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196546 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486547 }
6548}
6549
6550// Check that OnBeforeNetworkStart is only called once even if there is a
6551// redirect.
6552TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
tommycli59a63432015-11-06 00:10:556553 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486554
6555 TestDelegate d;
6556 {
6557 d.set_quit_on_redirect(true);
6558 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:196559 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556560 http_test_server()->GetURL("/server-redirect?echo"), DEFAULT_PRIORITY,
6561 &d));
[email protected]1826a402014-01-08 15:40:486562
[email protected]f7022f32014-08-21 16:32:196563 req->Start();
[email protected]1826a402014-01-08 15:40:486564 base::RunLoop().Run();
6565
6566 EXPECT_EQ(1, d.received_before_network_start_count());
6567 EXPECT_EQ(0, d.response_started_count());
6568 EXPECT_EQ(0, d.received_redirect_count());
6569
[email protected]f7022f32014-08-21 16:32:196570 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486571 base::RunLoop().Run();
6572
6573 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196574 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:486575 base::RunLoop().Run();
6576
6577 // Check that the redirect's new network transaction does not get propagated
6578 // to a second OnBeforeNetworkStart() notification.
6579 EXPECT_EQ(1, d.received_before_network_start_count());
6580
6581 EXPECT_EQ(1, d.response_started_count());
6582 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196583 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486584 }
6585}
6586
6587// Cancel the request after learning that the request would use the network.
6588TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556589 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486590
6591 TestDelegate d;
6592 {
6593 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556594 GURL test_url(http_test_server()->GetURL("/echo"));
davidben151423e2015-03-23 18:48:366595 scoped_ptr<URLRequest> req(
6596 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486597
[email protected]f7022f32014-08-21 16:32:196598 req->Start();
[email protected]1826a402014-01-08 15:40:486599 base::RunLoop().Run();
6600
6601 EXPECT_EQ(1, d.received_before_network_start_count());
6602 EXPECT_EQ(0, d.response_started_count());
6603
[email protected]f7022f32014-08-21 16:32:196604 req->Cancel();
[email protected]1826a402014-01-08 15:40:486605 base::RunLoop().Run();
6606
6607 EXPECT_EQ(1, d.response_started_count());
6608 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196609 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:486610 }
6611}
6612
[email protected]316c1e5e2012-09-12 15:17:446613TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:556614 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446615
6616 TestDelegate d;
6617 {
6618 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:196619 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556620 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6621 &d));
[email protected]f7022f32014-08-21 16:32:196622 req->Start();
[email protected]255620da2013-08-19 13:14:296623 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446624
6625 EXPECT_EQ(1, d.response_started_count());
6626 EXPECT_EQ(0, d.bytes_received());
6627 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196628 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446629 }
6630}
6631
6632TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:556633 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446634
6635 TestDelegate d;
6636 {
6637 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556638 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
davidben151423e2015-03-23 18:48:366639 scoped_ptr<URLRequest> req(
6640 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046641
[email protected]f7022f32014-08-21 16:32:196642 req->Start();
[email protected]255620da2013-08-19 13:14:296643 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446644
6645 EXPECT_EQ(1, d.received_redirect_count());
6646
[email protected]f7022f32014-08-21 16:32:196647 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296648 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446649
6650 EXPECT_EQ(1, d.response_started_count());
6651 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196652 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446653
[email protected]6cdfd7f2013-02-08 20:40:156654 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446655 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476656 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446657 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6658
6659 std::string contents;
[email protected]82f84b92013-08-30 18:23:506660 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446661 EXPECT_EQ(contents, d.data_received());
6662 }
6663}
6664
[email protected]79e1fd62013-06-20 06:50:046665TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:556666 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:046667
6668 TestDelegate d;
6669 {
6670 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556671 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
davidben151423e2015-03-23 18:48:366672 scoped_ptr<URLRequest> req(
6673 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046674
6675 EXPECT_FALSE(d.have_full_request_headers());
6676
[email protected]f7022f32014-08-21 16:32:196677 req->Start();
[email protected]255620da2013-08-19 13:14:296678 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046679
6680 EXPECT_EQ(1, d.received_redirect_count());
6681 EXPECT_TRUE(d.have_full_request_headers());
6682 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6683 d.ClearFullRequestHeaders();
6684
[email protected]f7022f32014-08-21 16:32:196685 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296686 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046687
tommycli59a63432015-11-06 00:10:556688 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:046689 EXPECT_EQ(1, d.response_started_count());
6690 EXPECT_TRUE(d.have_full_request_headers());
6691 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6692 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196693 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046694
6695 base::FilePath path;
6696 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476697 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046698 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6699
6700 std::string contents;
[email protected]82f84b92013-08-30 18:23:506701 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046702 EXPECT_EQ(contents, d.data_received());
6703 }
6704}
6705
[email protected]316c1e5e2012-09-12 15:17:446706TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:556707 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446708
6709 TestDelegate d;
6710 {
6711 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196712 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556713 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6714 &d));
[email protected]f7022f32014-08-21 16:32:196715 req->Start();
[email protected]255620da2013-08-19 13:14:296716 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446717
6718 EXPECT_EQ(1, d.received_redirect_count());
6719
[email protected]f7022f32014-08-21 16:32:196720 req->Cancel();
[email protected]255620da2013-08-19 13:14:296721 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446722
6723 EXPECT_EQ(1, d.response_started_count());
6724 EXPECT_EQ(0, d.bytes_received());
6725 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196726 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446727 }
6728}
6729
6730TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:556731 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446732
[email protected]3b23a222013-05-15 21:33:256733 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446734 {
6735 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196736 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556737 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6738 &d));
[email protected]316c1e5e2012-09-12 15:17:446739 HttpRequestHeaders headers;
6740 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196741 req->SetExtraRequestHeaders(headers);
6742 req->Start();
[email protected]255620da2013-08-19 13:14:296743 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256744
6745 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196746 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256747 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446748 }
6749
[email protected]3b23a222013-05-15 21:33:256750 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446751 {
6752 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196753 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556754 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6755 &d));
[email protected]316c1e5e2012-09-12 15:17:446756 HttpRequestHeaders headers;
6757 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196758 req->SetExtraRequestHeaders(headers);
6759 req->Start();
[email protected]255620da2013-08-19 13:14:296760 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446761
[email protected]f7022f32014-08-21 16:32:196762 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256763
6764 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196765 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256766 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446767 }
6768
[email protected]3b23a222013-05-15 21:33:256769 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446770 {
6771 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196772 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556773 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6774 &d));
[email protected]316c1e5e2012-09-12 15:17:446775 HttpRequestHeaders headers;
6776 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196777 req->SetExtraRequestHeaders(headers);
6778 req->Start();
[email protected]255620da2013-08-19 13:14:296779 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446780
[email protected]f7022f32014-08-21 16:32:196781 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256782
6783 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196784 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256785 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446786 }
6787}
6788
6789TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:556790 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446791
6792 // populate the cache
6793 {
6794 TestDelegate d;
6795 d.set_credentials(AuthCredentials(kUser, kSecret));
6796
[email protected]f7022f32014-08-21 16:32:196797 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556798 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196799 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446800
[email protected]255620da2013-08-19 13:14:296801 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446802
6803 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6804 }
6805
6806 // repeat request with end-to-end validation. since auth-basic results in a
6807 // cachable page, we expect this test to result in a 304. in which case, the
6808 // response should be fetched from the cache.
6809 {
6810 TestDelegate d;
6811 d.set_credentials(AuthCredentials(kUser, kSecret));
6812
[email protected]f7022f32014-08-21 16:32:196813 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556814 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196815 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6816 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446817
[email protected]255620da2013-08-19 13:14:296818 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446819
6820 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6821
6822 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196823 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446824 }
6825}
6826
6827// Check that Set-Cookie headers in 401 responses are respected.
6828// http://crbug.com/6450
6829TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:556830 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446831
6832 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:556833 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:446834
6835 // Request a page that will give a 401 containing a Set-Cookie header.
6836 // Verify that when the transaction is restarted, it includes the new cookie.
6837 {
[email protected]ceefd7fd2012-11-29 00:36:246838 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446839 TestURLRequestContext context(true);
6840 context.set_network_delegate(&network_delegate);
6841 context.Init();
6842
6843 TestDelegate d;
6844 d.set_credentials(AuthCredentials(kUser, kSecret));
6845
davidben151423e2015-03-23 18:48:366846 scoped_ptr<URLRequest> r(
6847 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196848 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446849
[email protected]255620da2013-08-19 13:14:296850 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446851
6852 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6853
6854 // Make sure we sent the cookie in the restarted transaction.
6855 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6856 != std::string::npos);
6857 }
6858
6859 // Same test as above, except this time the restart is initiated earlier
6860 // (without user intervention since identity is embedded in the URL).
6861 {
[email protected]ceefd7fd2012-11-29 00:36:246862 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446863 TestURLRequestContext context(true);
6864 context.set_network_delegate(&network_delegate);
6865 context.Init();
6866
6867 TestDelegate d;
6868
6869 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186870 replacements.SetUsernameStr("user2");
6871 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446872 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6873
davidben151423e2015-03-23 18:48:366874 scoped_ptr<URLRequest> r(
6875 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196876 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446877
[email protected]255620da2013-08-19 13:14:296878 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446879
6880 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6881
6882 // Make sure we sent the cookie in the restarted transaction.
6883 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6884 != std::string::npos);
6885 }
6886}
6887
[email protected]58e32bb2013-01-21 18:23:256888// Tests that load timing works as expected with auth and the cache.
6889TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:556890 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:256891
6892 // populate the cache
6893 {
6894 TestDelegate d;
6895 d.set_credentials(AuthCredentials(kUser, kSecret));
6896
[email protected]f7022f32014-08-21 16:32:196897 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556898 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196899 r->Start();
[email protected]58e32bb2013-01-21 18:23:256900
[email protected]255620da2013-08-19 13:14:296901 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256902
6903 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6904
6905 LoadTimingInfo load_timing_info_before_auth;
6906 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6907 &load_timing_info_before_auth));
6908 TestLoadTimingNotReused(load_timing_info_before_auth,
6909 CONNECT_TIMING_HAS_DNS_TIMES);
6910
6911 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196912 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256913 // The test server does not support keep alive sockets, so the second
6914 // request with auth should use a new socket.
6915 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6916 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6917 load_timing_info.socket_log_id);
6918 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6919 load_timing_info.connect_timing.connect_start);
6920 }
6921
[email protected]3b23a222013-05-15 21:33:256922 // Repeat request with end-to-end validation. Since auth-basic results in a
6923 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256924 // response should be fetched from the cache.
6925 {
6926 TestDelegate d;
6927 d.set_credentials(AuthCredentials(kUser, kSecret));
6928
[email protected]f7022f32014-08-21 16:32:196929 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556930 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196931 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6932 r->Start();
[email protected]58e32bb2013-01-21 18:23:256933
[email protected]255620da2013-08-19 13:14:296934 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256935
6936 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6937
6938 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196939 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256940
[email protected]3b23a222013-05-15 21:33:256941 // Since there was a request that went over the wire, the load timing
6942 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256943 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196944 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256945 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256946 }
6947}
6948
[email protected]316c1e5e2012-09-12 15:17:446949// In this test, we do a POST which the server will 302 redirect.
6950// The subsequent transaction should use GET, and should not send the
6951// Content-Type header.
6952// http://code.google.com/p/chromium/issues/detail?id=843
6953TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:556954 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446955
6956 const char kData[] = "hello world";
6957
6958 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196959 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556960 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY,
6961 &d));
[email protected]f7022f32014-08-21 16:32:196962 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076963 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446964
6965 // Set headers (some of which are specific to the POST).
6966 HttpRequestHeaders headers;
6967 headers.AddHeadersFromString(
6968 "Content-Type: multipart/form-data; "
6969 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6970 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6971 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6972 "Accept-Language: en-US,en\r\n"
6973 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6974 "Content-Length: 11\r\n"
6975 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196976 req->SetExtraRequestHeaders(headers);
6977 req->Start();
[email protected]255620da2013-08-19 13:14:296978 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446979
6980 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196981 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446982 EXPECT_EQ("text/html", mime_type);
6983
6984 const std::string& data = d.data_received();
6985
6986 // Check that the post-specific headers were stripped:
6987 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6988 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6989 EXPECT_FALSE(ContainsString(data, "Origin:"));
6990
6991 // These extra request headers should not have been stripped.
6992 EXPECT_TRUE(ContainsString(data, "Accept:"));
6993 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6994 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6995}
6996
jww5fe460ff2015-03-28 00:22:516997// The following tests check that we handle mutating the request for HTTP
6998// redirects as expected.
6999// See https://crbug.com/56373, https://crbug.com/102130, and
7000// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:447001
7002TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:557003 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447004
tommycli59a63432015-11-06 00:10:557005 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:517006 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557007 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:447008
7009 HTTPRedirectMethodTest(url, "POST", "GET", true);
7010 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7011 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517012
7013 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7014 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7015 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7016 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7017 std::string());
[email protected]316c1e5e2012-09-12 15:17:447018}
7019
7020TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:557021 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447022
tommycli59a63432015-11-06 00:10:557023 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:517024 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557025 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:447026
7027 HTTPRedirectMethodTest(url, "POST", "GET", true);
7028 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7029 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517030
7031 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7032 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7033 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7034 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7035 std::string());
[email protected]316c1e5e2012-09-12 15:17:447036}
7037
7038TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:557039 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447040
tommycli59a63432015-11-06 00:10:557041 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:517042 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557043 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:447044
7045 HTTPRedirectMethodTest(url, "POST", "GET", true);
7046 HTTPRedirectMethodTest(url, "PUT", "GET", true);
7047 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517048
7049 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7050 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7051 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7052 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7053 std::string());
[email protected]316c1e5e2012-09-12 15:17:447054}
7055
7056TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:557057 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447058
tommycli59a63432015-11-06 00:10:557059 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:517060 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557061 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:447062
7063 HTTPRedirectMethodTest(url, "POST", "POST", true);
7064 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7065 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517066
7067 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7068 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7069 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7070 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:447071}
7072
[email protected]0a17aab32014-04-24 03:32:377073TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:557074 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377075
tommycli59a63432015-11-06 00:10:557076 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:517077 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557078 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:377079
7080 HTTPRedirectMethodTest(url, "POST", "POST", true);
7081 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7082 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517083
7084 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7085 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7086 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7087 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:377088}
7089
7090// Make sure that 308 responses without bodies are not treated as redirects.
7091// Certain legacy apis that pre-date the response code expect this behavior
7092// (Like Google Drive).
7093TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:557094 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377095
7096 TestDelegate d;
tommycli59a63432015-11-06 00:10:557097 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:377098
davidben151423e2015-03-23 18:48:367099 scoped_ptr<URLRequest> request(
7100 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:377101
[email protected]f7022f32014-08-21 16:32:197102 request->Start();
[email protected]0a17aab32014-04-24 03:32:377103 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197104 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
7105 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:377106 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197107 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:377108 EXPECT_EQ("This is not a redirect.", d.data_received());
7109}
7110
[email protected]f878230e2014-04-03 15:36:147111TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:557112 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147113
tommycli59a63432015-11-06 00:10:557114 GURL original_url(
7115 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
7116 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:147117
7118 TestDelegate d;
7119 {
davidben151423e2015-03-23 18:48:367120 scoped_ptr<URLRequest> r(
7121 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:147122
[email protected]f7022f32014-08-21 16:32:197123 r->Start();
[email protected]f878230e2014-04-03 15:36:147124 base::RunLoop().Run();
7125
[email protected]f7022f32014-08-21 16:32:197126 EXPECT_EQ(2U, r->url_chain().size());
7127 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7128 EXPECT_EQ(OK, r->status().error());
7129 EXPECT_EQ(original_url, r->original_url());
7130 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:147131 }
7132}
7133
[email protected]cba24642014-08-15 20:49:597134TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557135 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597136
tommycli59a63432015-11-06 00:10:557137 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597138 GURL first_party_url("http://example.com");
7139
7140 TestDelegate d;
7141 {
davidben151423e2015-03-23 18:48:367142 scoped_ptr<URLRequest> r(
7143 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197144 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:597145
[email protected]f7022f32014-08-21 16:32:197146 r->Start();
[email protected]cba24642014-08-15 20:49:597147 base::RunLoop().Run();
7148
[email protected]f7022f32014-08-21 16:32:197149 EXPECT_EQ(2U, r->url_chain().size());
7150 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7151 EXPECT_EQ(OK, r->status().error());
7152 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597153 }
7154}
7155
7156TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557157 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597158
tommycli59a63432015-11-06 00:10:557159 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597160 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:557161 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:597162
7163 TestDelegate d;
7164 {
davidben151423e2015-03-23 18:48:367165 scoped_ptr<URLRequest> r(
7166 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197167 r->set_first_party_for_cookies(original_first_party_url);
7168 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597169 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7170
[email protected]f7022f32014-08-21 16:32:197171 r->Start();
[email protected]cba24642014-08-15 20:49:597172 base::RunLoop().Run();
7173
[email protected]f7022f32014-08-21 16:32:197174 EXPECT_EQ(2U, r->url_chain().size());
7175 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7176 EXPECT_EQ(OK, r->status().error());
7177 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597178 }
7179}
7180
[email protected]316c1e5e2012-09-12 15:17:447181TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:557182 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447183
7184 const char kData[] = "hello world";
7185
7186 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197187 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557188 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197189 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077190 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447191 HttpRequestHeaders headers;
7192 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517193 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197194 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447195
mmenkeed0498b2015-12-08 23:20:427196 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557197 req.get(), &default_network_delegate_,
7198 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427199 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7200 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447201
[email protected]f7022f32014-08-21 16:32:197202 req->Start();
[email protected]255620da2013-08-19 13:14:297203 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197204 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447205}
7206
7207TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:557208 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447209
7210 const char kData[] = "hello world";
7211
7212 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197213 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557214 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197215 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077216 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447217 HttpRequestHeaders headers;
7218 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517219 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197220 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447221
mmenkeed0498b2015-12-08 23:20:427222 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557223 req.get(), &default_network_delegate_,
7224 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097225 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:427226 "Very Good Reason"));
7227 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447228
[email protected]f7022f32014-08-21 16:32:197229 req->Start();
[email protected]255620da2013-08-19 13:14:297230 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197231 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447232 EXPECT_EQ(kData, d.data_received());
7233}
7234
7235// Check that default A-L header is sent.
7236TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557237 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447238
[email protected]8790210c2013-12-02 05:29:537239 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247240 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447241 TestURLRequestContext context(true);
7242 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437243 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447244 context.Init();
7245
7246 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197247 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557248 http_test_server()->GetURL("/echoheader?Accept-Language"),
7249 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197250 req->Start();
[email protected]255620da2013-08-19 13:14:297251 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447252 EXPECT_EQ("en", d.data_received());
7253}
7254
7255// Check that an empty A-L header is not sent. http://crbug.com/77365.
7256TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557257 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447258
[email protected]8790210c2013-12-02 05:29:537259 std::string empty_string; // Avoid most vexing parse on line below.
7260 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247261 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447262 TestURLRequestContext context(true);
7263 context.set_network_delegate(&network_delegate);
7264 context.Init();
7265 // We override the language after initialization because empty entries
7266 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437267 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447268
7269 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197270 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557271 http_test_server()->GetURL("/echoheader?Accept-Language"),
7272 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197273 req->Start();
[email protected]255620da2013-08-19 13:14:297274 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447275 EXPECT_EQ("None", d.data_received());
7276}
7277
7278// Check that if request overrides the A-L header, the default is not appended.
7279// See http://crbug.com/20894
7280TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557281 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447282
7283 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197284 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557285 http_test_server()->GetURL("/echoheader?Accept-Language"),
7286 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447287 HttpRequestHeaders headers;
7288 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197289 req->SetExtraRequestHeaders(headers);
7290 req->Start();
[email protected]255620da2013-08-19 13:14:297291 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447292 EXPECT_EQ(std::string("ru"), d.data_received());
7293}
7294
7295// Check that default A-E header is sent.
7296TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557297 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447298
7299 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197300 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557301 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7302 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447303 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197304 req->SetExtraRequestHeaders(headers);
7305 req->Start();
[email protected]255620da2013-08-19 13:14:297306 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447307 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7308}
7309
7310// Check that if request overrides the A-E header, the default is not appended.
7311// See http://crbug.com/47381
7312TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557313 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447314
7315 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197316 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557317 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7318 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447319 HttpRequestHeaders headers;
7320 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197321 req->SetExtraRequestHeaders(headers);
7322 req->Start();
[email protected]255620da2013-08-19 13:14:297323 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447324 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7325 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7326}
7327
[email protected]84f05432013-03-15 01:00:127328// Check that setting the A-C header sends the proper header.
7329TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:557330 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447331
7332 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197333 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557334 http_test_server()->GetURL("/echoheader?Accept-Charset"),
7335 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447336 HttpRequestHeaders headers;
7337 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197338 req->SetExtraRequestHeaders(headers);
7339 req->Start();
[email protected]255620da2013-08-19 13:14:297340 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447341 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7342}
7343
7344// Check that default User-Agent header is sent.
7345TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:557346 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447347
7348 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197349 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557350 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7351 &d));
[email protected]f7022f32014-08-21 16:32:197352 req->Start();
[email protected]255620da2013-08-19 13:14:297353 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197354 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377355 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447356}
7357
7358// Check that if request overrides the User-Agent header,
7359// the default is not appended.
marqf14fff8d2015-12-02 15:52:297360// TODO(crbug.com/564656) This test is flaky on iOS.
7361#if defined(OS_IOS)
7362#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
7363#else
7364#define MAYBE_OverrideUserAgent OverrideUserAgent
7365#endif
7366TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:557367 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447368
7369 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197370 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557371 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7372 &d));
[email protected]316c1e5e2012-09-12 15:17:447373 HttpRequestHeaders headers;
7374 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197375 req->SetExtraRequestHeaders(headers);
7376 req->Start();
[email protected]255620da2013-08-19 13:14:297377 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357378 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447379}
7380
[email protected]ee4c30d2012-11-07 15:08:437381// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7382// User-Agent header to be sent but does not send the Accept-Language and
7383// Accept-Charset headers.
7384TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:557385 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:437386
[email protected]ceefd7fd2012-11-29 00:36:247387 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437388 TestURLRequestContext context(true);
7389 context.set_network_delegate(&network_delegate);
7390 context.Init();
7391 // We override the HttpUserAgentSettings after initialization because empty
7392 // entries get overridden by Init().
7393 context.set_http_user_agent_settings(NULL);
7394
7395 struct {
7396 const char* request;
7397 const char* expected_response;
tommycli59a63432015-11-06 00:10:557398 } tests[] = {{"/echoheader?Accept-Language", "None"},
7399 {"/echoheader?Accept-Charset", "None"},
7400 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:437401
viettrungluue4a8b882014-10-16 06:17:387402 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437403 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197404 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557405 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197406 req->Start();
[email protected]255620da2013-08-19 13:14:297407 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437408 EXPECT_EQ(tests[i].expected_response, d.data_received())
7409 << " Request = \"" << tests[i].request << "\"";
7410 }
7411}
7412
[email protected]5033ab82013-03-22 20:17:467413// Make sure that URLRequest passes on its priority updates to
7414// newly-created jobs after the first one.
7415TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:557416 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:467417
7418 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197419 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557420 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197421 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467422
mmenkeed0498b2015-12-08 23:20:427423 scoped_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557424 req.get(), &default_network_delegate_,
7425 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427426 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7427 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:467428
[email protected]f7022f32014-08-21 16:32:197429 req->SetPriority(LOW);
7430 req->Start();
7431 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467432
mmenkeed0498b2015-12-08 23:20:427433 RequestPriority job_priority;
7434 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
7435 req.get(), &default_network_delegate_, &job_priority));
7436 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:467437
7438 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297439 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:427440 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:467441}
7442
[email protected]80abdad2014-03-15 00:20:547443// Check that creating a network request while entering/exiting suspend mode
7444// fails as it should. This is the only case where an HttpTransactionFactory
7445// does not return an HttpTransaction.
7446TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7447 // Create a new HttpNetworkLayer that thinks it's suspended.
mmenke2281f3762015-11-02 20:38:177448 scoped_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
7449 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547450 network_layer->OnSuspend();
7451
mmenkebc31a2c2015-10-29 13:44:457452 HttpCache http_cache(network_layer.Pass(),
mmenkee65e7af2015-10-13 17:16:427453 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547454
7455 TestURLRequestContext context(true);
7456 context.set_http_transaction_factory(&http_cache);
7457 context.Init();
7458
7459 TestDelegate d;
davidben151423e2015-03-23 18:48:367460 scoped_ptr<URLRequest> req(
7461 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197462 req->Start();
[email protected]80abdad2014-03-15 00:20:547463 base::RunLoop().Run();
7464
7465 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197466 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7467 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547468}
7469
mmenke2281f3762015-11-02 20:38:177470namespace {
[email protected]80abdad2014-03-15 00:20:547471
mmenke2281f3762015-11-02 20:38:177472// HttpTransactionFactory that synchronously fails to create transactions.
7473class FailingHttpTransactionFactory : public HttpTransactionFactory {
7474 public:
7475 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7476 : network_session_(network_session) {}
7477
7478 ~FailingHttpTransactionFactory() override {}
7479
7480 // HttpTransactionFactory methods:
7481 int CreateTransaction(RequestPriority priority,
7482 scoped_ptr<HttpTransaction>* trans) override {
7483 return ERR_FAILED;
7484 }
7485
7486 HttpCache* GetCache() override { return nullptr; }
7487
7488 HttpNetworkSession* GetSession() override { return network_session_; }
7489
7490 private:
7491 HttpNetworkSession* network_session_;
7492
7493 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7494};
7495
7496} // namespace
7497
7498// Check that when a request that fails to create an HttpTransaction can be
7499// cancelled while the failure notification is pending, and doesn't send two
7500// failure notifications.
7501//
7502// This currently only happens when in suspend mode and there's no cache, but
7503// just use a special HttpTransactionFactory, to avoid depending on those
7504// behaviors.
7505TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7506 FailingHttpTransactionFactory http_transaction_factory(
7507 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547508 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177509 context.set_http_transaction_factory(&http_transaction_factory);
7510 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547511 context.Init();
7512
7513 TestDelegate d;
davidben151423e2015-03-23 18:48:367514 scoped_ptr<URLRequest> req(
7515 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177516 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7517 // try to create an HttpNetworkTransaction synchronously on start).
7518 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197519 req->Start();
mmenke2281f3762015-11-02 20:38:177520 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547521 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177522 // Run pending error task, if there is one.
7523 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547524
7525 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177526 EXPECT_EQ(1, d.response_started_count());
7527 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
7528
7529 // NetworkDelegate should see the cancellation, but not the error.
7530 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7531 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547532}
7533
ttuttlec0c828492015-05-15 01:25:557534TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:557535 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557536
7537 TestDelegate d;
tommycli59a63432015-11-06 00:10:557538 GURL test_url(http_test_server()->GetURL("/"));
ttuttlec0c828492015-05-15 01:25:557539 scoped_ptr<URLRequest> req(
7540 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7541
7542 req->Start();
7543 base::RunLoop().Run();
7544
7545 EXPECT_TRUE(req->response_info().network_accessed);
7546}
7547
7548TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:557549 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557550
7551 // Populate the cache.
7552 TestDelegate d;
7553 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557554 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
ttuttlec0c828492015-05-15 01:25:557555 req->Start();
7556 base::RunLoop().Run();
7557
7558 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7559 EXPECT_TRUE(req->response_info().network_accessed);
7560 EXPECT_FALSE(req->response_info().was_cached);
7561
tommycli59a63432015-11-06 00:10:557562 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
ttuttlec0c828492015-05-15 01:25:557563 DEFAULT_PRIORITY, &d);
7564 req->Start();
7565 base::RunLoop().Run();
7566
7567 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7568 EXPECT_FALSE(req->response_info().network_accessed);
7569 EXPECT_TRUE(req->response_info().was_cached);
7570}
7571
7572TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:557573 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557574
7575 TestDelegate d;
tommycli59a63432015-11-06 00:10:557576 GURL test_url(http_test_server()->GetURL("/"));
ttuttlec0c828492015-05-15 01:25:557577 scoped_ptr<URLRequest> req(
7578 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7579 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7580
7581 req->Start();
7582 base::RunLoop().Run();
7583
7584 EXPECT_FALSE(req->response_info().network_accessed);
7585}
7586
bengr1bf8e942014-11-07 01:36:507587class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7588 public:
7589 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7590 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7591 // tests into the factory tests.
7592 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7593 }
7594
7595 void SetUpFactory() override {
7596 interceptor_ = new MockURLRequestInterceptor();
7597 job_factory_.reset(new URLRequestInterceptingJobFactory(
7598 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
7599 }
7600
7601 MockURLRequestInterceptor* interceptor() const {
7602 return interceptor_;
7603 }
7604
7605 private:
7606 MockURLRequestInterceptor* interceptor_;
7607};
7608
7609TEST_F(URLRequestInterceptorTestHTTP,
7610 NetworkDelegateNotificationOnRedirectIntercept) {
7611 interceptor()->set_intercept_redirect(true);
7612 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7613 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7614
tommycli59a63432015-11-06 00:10:557615 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507616
7617 TestDelegate d;
7618 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557619 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507620 req->Start();
7621 base::RunLoop().Run();
7622
7623 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7624 // Check we got one good response
7625 EXPECT_TRUE(req->status().is_success());
7626 if (req->status().is_success())
7627 EXPECT_EQ(200, req->response_headers()->response_code());
7628
7629 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7630 EXPECT_EQ(1, d.response_started_count());
7631 EXPECT_EQ(0, d.received_redirect_count());
7632
7633 EXPECT_EQ(1, default_network_delegate()->created_requests());
7634 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7635 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7636}
7637
7638TEST_F(URLRequestInterceptorTestHTTP,
7639 NetworkDelegateNotificationOnErrorIntercept) {
7640 // Intercept that error and respond with an OK response.
7641 interceptor()->set_intercept_final_response(true);
7642 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7643 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7644 default_network_delegate()->set_can_be_intercepted_on_error(true);
7645
tommycli59a63432015-11-06 00:10:557646 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507647
7648 TestDelegate d;
7649 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557650 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:367651 &d));
bengr1bf8e942014-11-07 01:36:507652 req->set_method("GET");
7653 req->Start();
7654 base::RunLoop().Run();
7655
7656 EXPECT_TRUE(interceptor()->did_intercept_final());
7657
7658 // Check we received one good response.
7659 EXPECT_TRUE(req->status().is_success());
7660 if (req->status().is_success())
7661 EXPECT_EQ(200, req->response_headers()->response_code());
7662 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7663 EXPECT_EQ(1, d.response_started_count());
7664 EXPECT_EQ(0, d.received_redirect_count());
7665
7666 EXPECT_EQ(1, default_network_delegate()->created_requests());
7667 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7668 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7669}
7670
7671TEST_F(URLRequestInterceptorTestHTTP,
7672 NetworkDelegateNotificationOnResponseIntercept) {
7673 // Intercept that error and respond with an OK response.
7674 interceptor()->set_intercept_final_response(true);
7675
7676 // Intercept with a real URLRequestHttpJob.
7677 interceptor()->set_use_url_request_http_job(true);
7678
tommycli59a63432015-11-06 00:10:557679 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507680
7681 TestDelegate d;
7682 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557683 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507684 req->set_method("GET");
7685 req->Start();
7686 base::RunLoop().Run();
7687
7688 EXPECT_TRUE(interceptor()->did_intercept_final());
7689
7690 // Check we received one good response.
7691 EXPECT_TRUE(req->status().is_success());
7692 if (req->status().is_success())
7693 EXPECT_EQ(200, req->response_headers()->response_code());
7694 EXPECT_EQ("hello", d.data_received());
7695 EXPECT_EQ(1, d.response_started_count());
7696 EXPECT_EQ(0, d.received_redirect_count());
7697
7698 EXPECT_EQ(1, default_network_delegate()->created_requests());
7699 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7700 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7701}
7702
mkwst0c5eab872014-11-21 14:18:547703class URLRequestTestReferrerPolicy : public URLRequestTest {
7704 public:
7705 URLRequestTestReferrerPolicy() {}
7706
tommycli59a63432015-11-06 00:10:557707 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
7708 origin_server_.reset(new EmbeddedTestServer(type));
7709 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
7710 origin_server_->AddDefaultHandlers(
7711 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7712 } else {
7713 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7714 }
mkwst0c5eab872014-11-21 14:18:547715 ASSERT_TRUE(origin_server_->Start());
7716 }
7717
tommycli59a63432015-11-06 00:10:557718 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
7719 net::EmbeddedTestServer::Type dest_type) {
7720 origin_server_.reset(new EmbeddedTestServer(origin_type));
7721 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7722 origin_server_->AddDefaultHandlers(
7723 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7724 } else {
7725 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7726 }
mkwst0c5eab872014-11-21 14:18:547727 ASSERT_TRUE(origin_server_->Start());
7728
tommycli59a63432015-11-06 00:10:557729 destination_server_.reset(new EmbeddedTestServer(dest_type));
7730 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7731 destination_server_->AddDefaultHandlers(
7732 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7733 } else {
7734 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7735 }
mkwst0c5eab872014-11-21 14:18:547736 ASSERT_TRUE(destination_server_->Start());
7737 }
7738
7739 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7740 const GURL& referrer,
7741 const GURL& expected) {
7742 // Create and execute the request: we'll only have a |destination_server_|
7743 // if the origins are meant to be distinct. Otherwise, we'll use the
7744 // |origin_server_| for both endpoints.
7745 GURL destination_url =
tommycli59a63432015-11-06 00:10:557746 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
7747 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:547748 GURL origin_url =
tommycli59a63432015-11-06 00:10:557749 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:547750
7751 TestDelegate d;
7752 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367753 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547754 req->set_referrer_policy(policy);
7755 req->SetReferrer(referrer.spec());
7756 req->Start();
7757 base::RunLoop().Run();
7758
7759 EXPECT_EQ(1, d.response_started_count());
7760 EXPECT_EQ(1, d.received_redirect_count());
7761 EXPECT_EQ(destination_url, req->url());
7762 EXPECT_TRUE(req->status().is_success());
7763 EXPECT_EQ(200, req->response_headers()->response_code());
7764
7765 EXPECT_EQ(expected.spec(), req->referrer());
7766 if (expected.is_empty())
7767 EXPECT_EQ("None", d.data_received());
7768 else
7769 EXPECT_EQ(expected.spec(), d.data_received());
7770 }
7771
tommycli59a63432015-11-06 00:10:557772 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:547773
7774 private:
tommycli59a63432015-11-06 00:10:557775 scoped_ptr<EmbeddedTestServer> origin_server_;
7776 scoped_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:547777};
7778
7779TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:557780 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547781
7782 VerifyReferrerAfterRedirect(
7783 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557784 origin_server()->GetURL("/path/to/file.html"),
7785 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547786
7787 VerifyReferrerAfterRedirect(
7788 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
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 VerifyReferrerAfterRedirect(
7793 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557794 origin_server()->GetURL("/path/to/file.html"),
7795 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547796
7797 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557798 origin_server()->GetURL("/path/to/file.html"),
7799 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547800}
7801
tommycli59a63432015-11-06 00:10:557802TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
7803 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
7804 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547805
7806 VerifyReferrerAfterRedirect(
7807 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557808 origin_server()->GetURL("/path/to/file.html"),
7809 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547810
7811 VerifyReferrerAfterRedirect(
7812 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557813 origin_server()->GetURL("/path/to/file.html"),
7814 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547815
7816 VerifyReferrerAfterRedirect(
7817 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557818 origin_server()->GetURL("/path/to/file.html"),
7819 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547820
7821 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557822 origin_server()->GetURL("/path/to/file.html"),
7823 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547824}
7825
7826TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:557827 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547828
7829 VerifyReferrerAfterRedirect(
7830 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557831 origin_server()->GetURL("/path/to/file.html"),
7832 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547833
7834 VerifyReferrerAfterRedirect(
7835 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557836 origin_server()->GetURL("/path/to/file.html"),
7837 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547838
7839 VerifyReferrerAfterRedirect(
7840 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557841 origin_server()->GetURL("/path/to/file.html"),
7842 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547843
7844 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557845 origin_server()->GetURL("/path/to/file.html"),
7846 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547847}
7848
tommycli59a63432015-11-06 00:10:557849TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7850 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
7851 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547852
7853 VerifyReferrerAfterRedirect(
7854 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557855 origin_server()->GetURL("/path/to/file.html"),
7856 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547857
7858 VerifyReferrerAfterRedirect(
7859 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557860 origin_server()->GetURL("/path/to/file.html"),
7861 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547862
7863 VerifyReferrerAfterRedirect(
7864 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557865 origin_server()->GetURL("/path/to/file.html"),
7866 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547867
7868 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557869 origin_server()->GetURL("/path/to/file.html"),
7870 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547871}
7872
tommycli59a63432015-11-06 00:10:557873TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7874 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
7875 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547876
7877 VerifyReferrerAfterRedirect(
7878 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557879 origin_server()->GetURL("/path/to/file.html"),
7880 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547881
7882 VerifyReferrerAfterRedirect(
7883 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557884 origin_server()->GetURL("/path/to/file.html"),
7885 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547886
7887 VerifyReferrerAfterRedirect(
7888 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557889 origin_server()->GetURL("/path/to/file.html"),
7890 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547891
7892 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557893 origin_server()->GetURL("/path/to/file.html"),
7894 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547895}
7896
tommycli59a63432015-11-06 00:10:557897TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7898 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
7899 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547900
7901 VerifyReferrerAfterRedirect(
7902 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557903 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:547904
7905 VerifyReferrerAfterRedirect(
7906 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557907 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:547908
7909 VerifyReferrerAfterRedirect(
7910 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557911 origin_server()->GetURL("/path/to/file.html"),
7912 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547913
7914 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557915 origin_server()->GetURL("/path/to/file.html"),
7916 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547917}
7918
[email protected]73e0bba2009-02-19 22:57:097919class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507920 public:
[email protected]ef2bf422012-05-11 03:27:097921 HTTPSRequestTest() : default_context_(true) {
7922 default_context_.set_network_delegate(&default_network_delegate_);
7923 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507924 }
dcheng67be2b1f2014-10-27 21:47:297925 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507926
7927 protected:
[email protected]ceefd7fd2012-11-29 00:36:247928 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097929 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467930};
7931
[email protected]c044616e2013-02-20 02:01:267932TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:557933 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7934 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:227935 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117936 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467937
[email protected]ea224582008-12-07 20:25:467938 TestDelegate d;
7939 {
[email protected]f7022f32014-08-21 16:32:197940 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557941 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197942 r->Start();
7943 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467944
[email protected]255620da2013-08-19 13:14:297945 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467946
7947 EXPECT_EQ(1, d.response_started_count());
7948 EXPECT_FALSE(d.received_data_before_response());
7949 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197950 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197951 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197952 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197953 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197954 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467955 }
[email protected]ea224582008-12-07 20:25:467956}
7957
[email protected]5774ada2010-07-15 06:30:547958TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:557959 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7960 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
7961 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:227962 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117963 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337964
7965 bool err_allowed = true;
7966 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7967 TestDelegate d;
7968 {
7969 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197970 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557971 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337972
[email protected]f7022f32014-08-21 16:32:197973 r->Start();
7974 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337975
[email protected]255620da2013-08-19 13:14:297976 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337977
7978 EXPECT_EQ(1, d.response_started_count());
7979 EXPECT_FALSE(d.received_data_before_response());
7980 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177981 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337982 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197983 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177984 } else {
[email protected]bacff652009-03-31 17:50:337985 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177986 }
[email protected]bacff652009-03-31 17:50:337987 }
7988 }
7989}
7990
[email protected]5774ada2010-07-15 06:30:547991TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:557992 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7993 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
7994 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:227995 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117996 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337997
7998 // Iterate from false to true, just so that we do the opposite of the
7999 // previous test in order to increase test coverage.
8000 bool err_allowed = false;
8001 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8002 TestDelegate d;
8003 {
8004 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:198005 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558006 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338007
[email protected]f7022f32014-08-21 16:32:198008 r->Start();
8009 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338010
[email protected]255620da2013-08-19 13:14:298011 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338012
8013 EXPECT_EQ(1, d.response_started_count());
8014 EXPECT_FALSE(d.received_data_before_response());
8015 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178016 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338017 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198018 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178019 } else {
[email protected]bacff652009-03-31 17:50:338020 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178021 }
[email protected]bacff652009-03-31 17:50:338022 }
8023 }
8024}
[email protected]73e0bba2009-02-19 22:57:098025
tommycli59a63432015-11-06 00:10:558026// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
8027// security state. (see http://crbug.com/550977).
8028#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:448029// This tests that a load of www.google.com with a certificate error sets
8030// the |certificate_errors_are_fatal| flag correctly. This flag will cause
8031// the interstitial to be fatal.
8032TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
tommycli59a63432015-11-06 00:10:558033 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8034 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8035 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448036 ASSERT_TRUE(test_server.Start());
8037
8038 // We require that the URL be www.google.com in order to pick up the
8039 // preloaded HSTS entries in the TransportSecurityState. This means that we
8040 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:248041 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448042
8043 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248044 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448045 TestURLRequestContext context(true);
8046 context.set_network_delegate(&network_delegate);
8047 context.set_host_resolver(&host_resolver);
8048 TransportSecurityState transport_security_state;
8049 context.set_transport_security_state(&transport_security_state);
8050 context.Init();
8051
8052 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198053 scoped_ptr<URLRequest> r(context.CreateRequest(
8054 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368055 test_server.host_port_pair().port())),
8056 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448057
[email protected]f7022f32014-08-21 16:32:198058 r->Start();
8059 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448060
[email protected]255620da2013-08-19 13:14:298061 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448062
8063 EXPECT_EQ(1, d.response_started_count());
8064 EXPECT_FALSE(d.received_data_before_response());
8065 EXPECT_TRUE(d.have_certificate_errors());
8066 EXPECT_TRUE(d.certificate_errors_are_fatal());
8067}
8068
8069// This tests that cached HTTPS page loads do not cause any updates to the
8070// TransportSecurityState.
8071TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
8072 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
8073 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:558074 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8075 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8076 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448077 ASSERT_TRUE(test_server.Start());
8078
[email protected]9e6968d2014-05-07 21:46:268079 // We require that the URL be www.google.com in order to pick up the static
8080 // and dynamic STS and PKP entries in the TransportSecurityState. This means
8081 // that we have to use a MockHostResolver in order to direct www.google.com to
8082 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448083
8084 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248085 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448086 TestURLRequestContext context(true);
8087 context.set_network_delegate(&network_delegate);
8088 context.set_host_resolver(&host_resolver);
8089 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:268090
martijnc0d6b622015-06-30 19:14:408091 TransportSecurityState::STSState static_sts_state;
8092 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268093 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408094 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:448095 context.set_transport_security_state(&transport_security_state);
8096 context.Init();
8097
martijnc0d6b622015-06-30 19:14:408098 TransportSecurityState::STSState dynamic_sts_state;
8099 TransportSecurityState::PKPState dynamic_pkp_state;
8100 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
8101 &dynamic_sts_state));
8102 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
8103 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268104
[email protected]316c1e5e2012-09-12 15:17:448105 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198106 scoped_ptr<URLRequest> r(context.CreateRequest(
8107 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368108 test_server.host_port_pair().port())),
8109 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448110
[email protected]f7022f32014-08-21 16:32:198111 r->Start();
8112 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448113
[email protected]255620da2013-08-19 13:14:298114 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448115
8116 EXPECT_EQ(1, d.response_started_count());
8117 EXPECT_FALSE(d.received_data_before_response());
8118 EXPECT_TRUE(d.have_certificate_errors());
8119 EXPECT_TRUE(d.certificate_errors_are_fatal());
8120
[email protected]9e6968d2014-05-07 21:46:268121 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408122 TransportSecurityState::STSState new_static_sts_state;
8123 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268124 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408125 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8126 TransportSecurityState::STSState new_dynamic_sts_state;
8127 TransportSecurityState::PKPState new_dynamic_pkp_state;
8128 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8129 "www.google.com", &new_dynamic_sts_state));
8130 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8131 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268132
martijnc0d6b622015-06-30 19:14:408133 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8134 EXPECT_EQ(new_static_sts_state.include_subdomains,
8135 static_sts_state.include_subdomains);
8136 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8137 static_pkp_state.include_subdomains);
8138 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.spki_hashes,
8139 static_pkp_state.spki_hashes));
8140 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.bad_spki_hashes,
8141 static_pkp_state.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:448142}
8143
[email protected]8ccc69f2012-11-28 19:52:148144// Make sure HSTS preserves a POST request's method and body.
8145TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8146 static const char kData[] = "hello world";
8147
tommycli59a63432015-11-06 00:10:558148 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8149 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228150 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148151 ASSERT_TRUE(test_server.Start());
8152
8153
8154 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8155 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:558156 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:228157 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148158 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148159
8160 // Force https for www.somewhere.com.
8161 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208162 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8163 bool include_subdomains = false;
8164 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8165 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148166
8167 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8168
8169 TestURLRequestContext context(true);
8170 context.set_host_resolver(&host_resolver);
8171 context.set_transport_security_state(&transport_security_state);
8172 context.set_network_delegate(&network_delegate);
8173 context.Init();
8174
8175 TestDelegate d;
8176 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8177 // cause a certificate error. Ignore the error.
8178 d.set_allow_certificate_errors(true);
8179
[email protected]f7022f32014-08-21 16:32:198180 scoped_ptr<URLRequest> req(context.CreateRequest(
8181 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368182 test_server.host_port_pair().port())),
8183 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198184 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078185 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148186
[email protected]f7022f32014-08-21 16:32:198187 req->Start();
[email protected]255620da2013-08-19 13:14:298188 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148189
[email protected]f7022f32014-08-21 16:32:198190 EXPECT_EQ("https", req->url().scheme());
8191 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148192 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408193
8194 LoadTimingInfo load_timing_info;
8195 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8196 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8197 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148198}
8199
rob4e0be1f2014-09-11 23:40:228200// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8201TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8202 static const char kOriginHeaderValue[] = "http://www.example.com";
8203
tommycli59a63432015-11-06 00:10:558204 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8205 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:228206 ASSERT_TRUE(test_server.Start());
8207
8208 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8209 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:558210 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
8211 // default.
rob4e0be1f2014-09-11 23:40:228212 MockHostResolver host_resolver;
8213
8214 TransportSecurityState transport_security_state;
8215 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8216 bool include_subdomains = false;
8217 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8218
8219 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8220
8221 MockCertVerifier cert_verifier;
8222 cert_verifier.set_default_result(OK);
8223
8224 TestURLRequestContext context(true);
8225 context.set_host_resolver(&host_resolver);
8226 context.set_transport_security_state(&transport_security_state);
8227 context.set_network_delegate(&network_delegate);
8228 context.set_cert_verifier(&cert_verifier);
8229 context.Init();
8230
8231 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8232 test_server.host_port_pair().port()));
8233 url::Replacements<char> replacements;
8234 const char kNewScheme[] = "https";
8235 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8236 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8237
8238 TestDelegate d;
8239 // Quit on redirect to allow response header inspection upon redirect.
8240 d.set_quit_on_redirect(true);
8241
davidben151423e2015-03-23 18:48:368242 scoped_ptr<URLRequest> req(
8243 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228244 // Set Origin header to simulate a cross-origin request.
8245 HttpRequestHeaders request_headers;
8246 request_headers.SetHeader("Origin", kOriginHeaderValue);
8247 req->SetExtraRequestHeaders(request_headers);
8248
8249 req->Start();
8250 base::RunLoop().Run();
8251
8252 EXPECT_EQ(1, d.received_redirect_count());
8253
8254 const HttpResponseHeaders* headers = req->response_headers();
8255 std::string redirect_location;
8256 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8257 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8258
8259 std::string received_cors_header;
8260 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8261 &received_cors_header));
8262 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8263}
8264
Adam Ricecb76ac62015-02-20 05:33:258265// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
8266// are performed in net/websockets/websocket_end_to_end_test.cc.
8267TEST(WebSocketURLRequestTest, HSTSApplied) {
8268 TestNetworkDelegate network_delegate;
8269 TransportSecurityState transport_security_state;
8270 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8271 bool include_subdomains = false;
8272 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8273 TestURLRequestContext context(true);
8274 context.set_transport_security_state(&transport_security_state);
8275 context.set_network_delegate(&network_delegate);
8276 context.Init();
8277 GURL ws_url("ws://example.net/echo");
8278 TestDelegate delegate;
8279 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:368280 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:258281 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
8282 EXPECT_TRUE(ws_url.SchemeIs("wss"));
8283}
8284
[email protected]316c1e5e2012-09-12 15:17:448285namespace {
8286
8287class SSLClientAuthTestDelegate : public TestDelegate {
8288 public:
8289 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8290 }
dchengb03027d2014-10-21 12:00:208291 void OnCertificateRequested(URLRequest* request,
8292 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448293 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178294 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448295 }
8296 int on_certificate_requested_count() {
8297 return on_certificate_requested_count_;
8298 }
8299 private:
8300 int on_certificate_requested_count_;
8301};
8302
8303} // namespace
8304
8305// TODO(davidben): Test the rest of the code. Specifically,
8306// - Filtering which certificates to select.
8307// - Sending a certificate back.
8308// - Getting a certificate request in an SSL renegotiation sending the
8309// HTTP request.
8310TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:558311 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8312 net::SSLServerConfig ssl_config;
8313 ssl_config.require_client_cert = true;
8314 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
8315 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228316 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448317 ASSERT_TRUE(test_server.Start());
8318
8319 SSLClientAuthTestDelegate d;
8320 {
[email protected]f7022f32014-08-21 16:32:198321 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558322 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448323
[email protected]f7022f32014-08-21 16:32:198324 r->Start();
8325 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448326
[email protected]255620da2013-08-19 13:14:298327 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448328
8329 EXPECT_EQ(1, d.on_certificate_requested_count());
8330 EXPECT_FALSE(d.received_data_before_response());
8331 EXPECT_EQ(0, d.bytes_received());
8332
8333 // Send no certificate.
8334 // TODO(davidben): Get temporary client cert import (with keys) working on
8335 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:548336 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:448337
[email protected]255620da2013-08-19 13:14:298338 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448339
8340 EXPECT_EQ(1, d.response_started_count());
8341 EXPECT_FALSE(d.received_data_before_response());
8342 EXPECT_NE(0, d.bytes_received());
8343 }
8344}
8345
8346TEST_F(HTTPSRequestTest, ResumeTest) {
8347 // Test that we attempt a session resume when making two connections to the
8348 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228349 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448350 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228351 SpawnedTestServer test_server(
8352 SpawnedTestServer::TYPE_HTTPS,
8353 ssl_options,
8354 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448355 ASSERT_TRUE(test_server.Start());
8356
8357 SSLClientSocket::ClearSessionCache();
8358
8359 {
8360 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198361 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368362 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448363
[email protected]f7022f32014-08-21 16:32:198364 r->Start();
8365 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448366
[email protected]255620da2013-08-19 13:14:298367 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448368
8369 EXPECT_EQ(1, d.response_started_count());
8370 }
8371
8372 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8373 CloseAllConnections();
8374
8375 {
8376 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198377 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368378 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448379
[email protected]f7022f32014-08-21 16:32:198380 r->Start();
8381 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448382
[email protected]255620da2013-08-19 13:14:298383 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448384
8385 // The response will look like;
8386 // insert abc
8387 // lookup abc
8388 // insert xyz
8389 //
8390 // With a newline at the end which makes the split think that there are
8391 // four lines.
8392
8393 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298394 std::vector<std::string> lines = base::SplitString(
8395 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448396 ASSERT_EQ(4u, lines.size()) << d.data_received();
8397
8398 std::string session_id;
8399
8400 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298401 std::vector<std::string> parts = base::SplitString(
8402 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448403 ASSERT_EQ(2u, parts.size());
8404 if (i == 0) {
8405 EXPECT_EQ("insert", parts[0]);
8406 session_id = parts[1];
8407 } else {
8408 EXPECT_EQ("lookup", parts[0]);
8409 EXPECT_EQ(session_id, parts[1]);
8410 }
8411 }
8412 }
8413}
8414
Adam Langley32352ad2014-10-14 22:31:008415// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8416// the result of fetching "ssl-session-cache" from the test server, indicates
8417// that exactly two different sessions were inserted, with no lookups etc.
8418static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298419 std::vector<std::string> lines = base::SplitString(
8420 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008421 ASSERT_EQ(3u, lines.size()) << session_info;
8422
8423 std::string session_id;
8424 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298425 std::vector<std::string> parts = base::SplitString(
8426 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008427 ASSERT_EQ(2u, parts.size());
8428 EXPECT_EQ("insert", parts[0]);
8429 if (i == 0) {
8430 session_id = parts[1];
8431 } else {
8432 EXPECT_NE(session_id, parts[1]);
8433 }
8434 }
8435}
8436
[email protected]316c1e5e2012-09-12 15:17:448437TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8438 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8439 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228440 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448441 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228442 SpawnedTestServer test_server(
8443 SpawnedTestServer::TYPE_HTTPS,
8444 ssl_options,
8445 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448446 ASSERT_TRUE(test_server.Start());
8447
8448 SSLClientSocket::ClearSessionCache();
8449
8450 {
8451 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198452 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368453 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448454
[email protected]f7022f32014-08-21 16:32:198455 r->Start();
8456 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448457
[email protected]255620da2013-08-19 13:14:298458 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448459
8460 EXPECT_EQ(1, d.response_started_count());
8461 }
8462
8463 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8464 HttpNetworkSession::Params params;
8465 params.host_resolver = default_context_.host_resolver();
8466 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118467 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:448468 params.proxy_service = default_context_.proxy_service();
8469 params.ssl_config_service = default_context_.ssl_config_service();
8470 params.http_auth_handler_factory =
8471 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:418472 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:448473 params.http_server_properties = default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:448474
mmenkee65e7af2015-10-13 17:16:428475 HttpNetworkSession network_session(params);
[email protected]cba24642014-08-15 20:49:598476 scoped_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428477 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448478
8479 default_context_.set_http_transaction_factory(cache.get());
8480
8481 {
8482 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198483 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368484 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448485
[email protected]f7022f32014-08-21 16:32:198486 r->Start();
8487 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448488
[email protected]255620da2013-08-19 13:14:298489 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448490
8491 // The response will look like;
8492 // insert abc
8493 // insert xyz
8494 //
8495 // With a newline at the end which makes the split think that there are
8496 // three lines.
8497
8498 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008499 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448500 }
8501}
8502
davidben8ecc3072014-09-03 23:19:098503#if defined(OS_WIN)
8504
8505namespace {
8506
8507bool IsECDSACipherSuite(uint16_t cipher_suite) {
8508 const char* key_exchange;
8509 const char* cipher;
8510 const char* mac;
8511 bool is_aead;
8512 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
8513 return std::string(key_exchange).find("ECDSA") != std::string::npos;
8514}
8515
8516} // namespace
8517
8518// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
8519// verified.
davidben9399c952014-10-07 04:09:118520TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:098521 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
8522 LOG(INFO) << "Skipping test on this version.";
8523 return;
8524 }
8525
tommycli59a63432015-11-06 00:10:558526 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8527 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
davidben8ecc3072014-09-03 23:19:098528 ASSERT_TRUE(test_server.Start());
8529
8530 TestDelegate d;
8531 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558532 test_server.GetURL("/client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:098533 r->Start();
8534 EXPECT_TRUE(r->is_pending());
8535
8536 base::RunLoop().Run();
8537
8538 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298539 std::vector<std::string> lines = base::SplitString(
8540 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
davidben8ecc3072014-09-03 23:19:098541
8542 for (size_t i = 0; i < lines.size(); i++) {
8543 int cipher_suite;
8544 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
8545 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
8546 << "ClientHello advertised " << cipher_suite;
8547 }
8548}
8549
8550#endif // OS_WIN
8551
Adam Langley32352ad2014-10-14 22:31:008552class TestSSLConfigService : public SSLConfigService {
8553 public:
8554 TestSSLConfigService(bool ev_enabled,
8555 bool online_rev_checking,
8556 bool rev_checking_required_local_anchors)
8557 : ev_enabled_(ev_enabled),
8558 online_rev_checking_(online_rev_checking),
8559 rev_checking_required_local_anchors_(
8560 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:028561 min_version_(kDefaultSSLVersionMin),
8562 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
8563
avibf0746c2015-12-09 19:53:148564 void set_min_version(uint16_t version) { min_version_ = version; }
Adam Langley32352ad2014-10-14 22:31:008565
avibf0746c2015-12-09 19:53:148566 void set_fallback_min_version(uint16_t version) {
Adam Langley32352ad2014-10-14 22:31:008567 fallback_min_version_ = version;
8568 }
8569
8570 // SSLConfigService:
dchengb03027d2014-10-21 12:00:208571 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:008572 *config = SSLConfig();
8573 config->rev_checking_enabled = online_rev_checking_;
8574 config->verify_ev_cert = ev_enabled_;
8575 config->rev_checking_required_local_anchors =
8576 rev_checking_required_local_anchors_;
8577 if (fallback_min_version_) {
8578 config->version_fallback_min = fallback_min_version_;
8579 }
Adam Langleyac6f24b42014-10-31 20:24:028580 if (min_version_) {
8581 config->version_min = min_version_;
8582 }
Adam Langley32352ad2014-10-14 22:31:008583 }
8584
8585 protected:
dchengb03027d2014-10-21 12:00:208586 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:008587
8588 private:
8589 const bool ev_enabled_;
8590 const bool online_rev_checking_;
8591 const bool rev_checking_required_local_anchors_;
avibf0746c2015-12-09 19:53:148592 uint16_t min_version_;
8593 uint16_t fallback_min_version_;
Adam Langley32352ad2014-10-14 22:31:008594};
8595
8596class FallbackTestURLRequestContext : public TestURLRequestContext {
8597 public:
8598 explicit FallbackTestURLRequestContext(bool delay_initialization)
8599 : TestURLRequestContext(delay_initialization) {}
8600
avibf0746c2015-12-09 19:53:148601 void set_fallback_min_version(uint16_t version) {
Adam Langley32352ad2014-10-14 22:31:008602 TestSSLConfigService *ssl_config_service =
8603 new TestSSLConfigService(true /* check for EV */,
8604 false /* online revocation checking */,
8605 false /* require rev. checking for local
8606 anchors */);
8607 ssl_config_service->set_fallback_min_version(version);
8608 set_ssl_config_service(ssl_config_service);
8609 }
8610};
8611
[email protected]48d2b7c52014-06-27 01:16:558612class HTTPSFallbackTest : public testing::Test {
8613 public:
Adam Langley32352ad2014-10-14 22:31:008614 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298615 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558616
8617 protected:
8618 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8619 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008620 context_.Init();
8621 delegate_.set_allow_certificate_errors(true);
8622
[email protected]48d2b7c52014-06-27 01:16:558623 SpawnedTestServer test_server(
8624 SpawnedTestServer::TYPE_HTTPS,
8625 ssl_options,
8626 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8627 ASSERT_TRUE(test_server.Start());
8628
tommycli59a63432015-11-06 00:10:558629 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
8630 &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558631 request_->Start();
8632
8633 base::RunLoop().Run();
8634 }
8635
avibf0746c2015-12-09 19:53:148636 void set_fallback_min_version(uint16_t version) {
Adam Langley32352ad2014-10-14 22:31:008637 context_.set_fallback_min_version(version);
8638 }
8639
[email protected]48d2b7c52014-06-27 01:16:558640 void ExpectConnection(int version) {
8641 EXPECT_EQ(1, delegate_.response_started_count());
8642 EXPECT_NE(0, delegate_.bytes_received());
8643 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8644 request_->ssl_info().connection_status));
8645 EXPECT_TRUE(request_->ssl_info().connection_status &
8646 SSL_CONNECTION_VERSION_FALLBACK);
8647 }
8648
8649 void ExpectFailure(int error) {
8650 EXPECT_EQ(1, delegate_.response_started_count());
8651 EXPECT_FALSE(request_->status().is_success());
8652 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8653 EXPECT_EQ(error, request_->status().error());
8654 }
8655
8656 private:
8657 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008658 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558659 scoped_ptr<URLRequest> request_;
8660};
8661
davidbenb127ca82015-06-15 19:05:428662// Tests the TLS 1.0 fallback doesn't happen.
8663TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558664 SpawnedTestServer::SSLOptions ssl_options(
8665 SpawnedTestServer::SSLOptions::CERT_OK);
8666 ssl_options.tls_intolerant =
8667 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8668
8669 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428670 ExpectFailure(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION);
8671}
8672
8673// Tests the TLS 1.1 fallback.
8674TEST_F(HTTPSFallbackTest, TLSv1_1Fallback) {
davidbenb127ca82015-06-15 19:05:428675 SpawnedTestServer::SSLOptions ssl_options(
8676 SpawnedTestServer::SSLOptions::CERT_OK);
8677 ssl_options.tls_intolerant =
8678 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8679
8680 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8681 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
8682}
8683
8684// Tests that the TLS 1.1 fallback triggers on closed connections.
8685TEST_F(HTTPSFallbackTest, TLSv1_1FallbackClosed) {
davidbenb127ca82015-06-15 19:05:428686 SpawnedTestServer::SSLOptions ssl_options(
8687 SpawnedTestServer::SSLOptions::CERT_OK);
8688 ssl_options.tls_intolerant =
8689 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8690 ssl_options.tls_intolerance_type =
8691 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8692
8693 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8694 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558695}
8696
8697// This test is disabled on Android because the remote test server doesn't cause
8698// a TCP reset.
8699#if !defined(OS_ANDROID)
davidbenb127ca82015-06-15 19:05:428700// Tests fallback to TLS 1.1 on connection reset.
8701TEST_F(HTTPSFallbackTest, TLSv1_1FallbackReset) {
[email protected]48d2b7c52014-06-27 01:16:558702 SpawnedTestServer::SSLOptions ssl_options(
8703 SpawnedTestServer::SSLOptions::CERT_OK);
8704 ssl_options.tls_intolerant =
davidbenb127ca82015-06-15 19:05:428705 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
[email protected]48d2b7c52014-06-27 01:16:558706 ssl_options.tls_intolerance_type =
8707 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8708
8709 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428710 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558711}
8712#endif // !OS_ANDROID
8713
[email protected]12833302014-07-02 01:57:318714// Tests that we don't fallback on handshake failure with servers that implement
8715// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558716TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558717 SpawnedTestServer::SSLOptions ssl_options(
8718 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438719 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558720 // a version fallback.
8721 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438722 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558723 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8724 // connections are rejected.
8725 ssl_options.fallback_scsv_enabled = true;
8726
8727 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8728
8729 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8730 // intolerance. If the fallback SCSV is processed when the original error
8731 // that caused the fallback should be returned, which should be
8732 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8733 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8734}
8735
[email protected]12833302014-07-02 01:57:318736// Tests that we don't fallback on connection closed with servers that implement
8737// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318738TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318739 SpawnedTestServer::SSLOptions ssl_options(
8740 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438741 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318742 // a version fallback.
8743 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438744 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318745 ssl_options.tls_intolerance_type =
8746 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8747 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8748 // connections are rejected.
8749 ssl_options.fallback_scsv_enabled = true;
8750
8751 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8752
8753 // The original error should be replayed on rejected fallback.
8754 ExpectFailure(ERR_CONNECTION_CLOSED);
8755}
8756
davidbenb937d6c2015-05-14 04:53:428757// Test that fallback probe connections don't cause sessions to be cached.
8758TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008759 SpawnedTestServer::SSLOptions ssl_options(
8760 SpawnedTestServer::SSLOptions::CERT_OK);
8761 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428762 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008763 ssl_options.tls_intolerance_type =
8764 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8765 ssl_options.record_resume = true;
8766
8767 SpawnedTestServer test_server(
8768 SpawnedTestServer::TYPE_HTTPS,
8769 ssl_options,
8770 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8771 ASSERT_TRUE(test_server.Start());
8772
8773 SSLClientSocket::ClearSessionCache();
8774
davidbenb937d6c2015-05-14 04:53:428775 // Make a connection that does a probe fallback to TLSv1 but fails because
8776 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008777 // be inserted locally.
8778 {
8779 TestDelegate delegate;
8780 FallbackTestURLRequestContext context(true);
8781
davidbenb937d6c2015-05-14 04:53:428782 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008783 context.Init();
8784 scoped_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558785 test_server.GetURL("/"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008786 request->Start();
8787
8788 base::RunLoop().Run();
8789
8790 EXPECT_EQ(1, delegate.response_started_count());
8791 EXPECT_FALSE(request->status().is_success());
8792 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8793 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8794 request->status().error());
8795 }
8796
davidbenb937d6c2015-05-14 04:53:428797 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008798 {
8799 TestDelegate delegate;
8800 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428801 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008802
8803 context.Init();
davidben151423e2015-03-23 18:48:368804 scoped_ptr<URLRequest> request(context.CreateRequest(
8805 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008806 request->Start();
8807
8808 base::RunLoop().Run();
8809
8810 EXPECT_EQ(1, delegate.response_started_count());
8811 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428812 EXPECT_EQ(
8813 SSL_CONNECTION_VERSION_TLS1,
8814 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008815 EXPECT_TRUE(request->ssl_info().connection_status &
8816 SSL_CONNECTION_VERSION_FALLBACK);
8817
8818 std::vector<std::string> lines;
8819 // If no sessions were cached then the server should have seen two sessions
8820 // inserted with no lookups.
8821 AssertTwoDistinctSessionsInserted(delegate.data_received());
8822 }
8823}
8824
[email protected]a8fed1742013-12-27 02:14:248825class HTTPSSessionTest : public testing::Test {
8826 public:
8827 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598828 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248829
8830 default_context_.set_network_delegate(&default_network_delegate_);
8831 default_context_.set_cert_verifier(&cert_verifier_);
8832 default_context_.Init();
8833 }
dcheng67be2b1f2014-10-27 21:47:298834 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248835
8836 protected:
8837 MockCertVerifier cert_verifier_;
8838 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8839 TestURLRequestContext default_context_;
8840};
8841
8842// Tests that session resumption is not attempted if an invalid certificate
8843// is presented.
8844TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8845 SpawnedTestServer::SSLOptions ssl_options;
8846 ssl_options.record_resume = true;
8847 SpawnedTestServer test_server(
8848 SpawnedTestServer::TYPE_HTTPS,
8849 ssl_options,
8850 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8851 ASSERT_TRUE(test_server.Start());
8852
8853 SSLClientSocket::ClearSessionCache();
8854
8855 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598856 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248857 {
8858 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198859 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368860 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248861
[email protected]f7022f32014-08-21 16:32:198862 r->Start();
8863 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248864
8865 base::RunLoop().Run();
8866
8867 EXPECT_EQ(1, d.response_started_count());
8868 }
8869
8870 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8871 CloseAllConnections();
8872
8873 // Now change the certificate to be acceptable (so that the response is
8874 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598875 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248876 {
8877 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198878 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368879 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248880
[email protected]f7022f32014-08-21 16:32:198881 r->Start();
8882 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248883
8884 base::RunLoop().Run();
8885
8886 // The response will look like;
8887 // insert abc
8888 // insert xyz
8889 //
8890 // With a newline at the end which makes the split think that there are
8891 // three lines.
8892 //
8893 // If a session was presented (eg: a bug), then the response would look
8894 // like;
8895 // insert abc
8896 // lookup abc
8897 // insert xyz
8898
8899 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008900 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248901 }
8902}
8903
[email protected]dffe8242012-03-20 15:14:278904// This the fingerprint of the "Testing CA" certificate used by the testserver.
8905// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268906static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278907 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8908 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8909
[email protected]51523f52013-07-31 21:57:288910// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8911// testserver.
8912static const SHA256HashValue kOCSPTestCertSPKI = { {
8913 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8914 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8915 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8916 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8917} };
8918
[email protected]dffe8242012-03-20 15:14:278919// This is the policy OID contained in the certificates that testserver
8920// generates.
8921static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8922
8923class HTTPSOCSPTest : public HTTPSRequestTest {
8924 public:
8925 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098926 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088927 ev_test_policy_(
8928 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8929 kOCSPTestCertFingerprint,
8930 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028931 }
8932
dcheng67be2b1f2014-10-27 21:47:298933 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098934 SetupContext(&context_);
8935 context_.Init();
[email protected]dffe8242012-03-20 15:14:278936
[email protected]cba24642014-08-15 20:49:598937 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208938 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428939 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508940 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278941
davidben71f35ff2015-04-17 20:54:488942#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098943 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278944 EnsureNSSHttpIOInit();
8945#endif
8946 }
8947
[email protected]ce7d0cbc2013-05-03 18:57:228948 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278949 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538950 // We always overwrite out_cert_status.
8951 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228952 SpawnedTestServer test_server(
8953 SpawnedTestServer::TYPE_HTTPS,
8954 ssl_options,
8955 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278956 ASSERT_TRUE(test_server.Start());
8957
8958 TestDelegate d;
8959 d.set_allow_certificate_errors(true);
tommycli59a63432015-11-06 00:10:558960 scoped_ptr<URLRequest> r(
8961 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198962 r->Start();
[email protected]dffe8242012-03-20 15:14:278963
[email protected]255620da2013-08-19 13:14:298964 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278965
8966 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198967 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278968 }
8969
dcheng67be2b1f2014-10-27 21:47:298970 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488971#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278972 ShutdownNSSHttpIO();
8973#endif
8974 }
8975
[email protected]a13234c2012-03-20 21:45:028976 protected:
8977 // SetupContext configures the URLRequestContext that will be used for making
8978 // connetions to testserver. This can be overridden in test subclasses for
8979 // different behaviour.
8980 virtual void SetupContext(URLRequestContext* context) {
8981 context->set_ssl_config_service(
8982 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208983 true /* online revocation checking */,
8984 false /* require rev. checking for local
8985 anchors */));
[email protected]a13234c2012-03-20 21:45:028986 }
8987
[email protected]dffe8242012-03-20 15:14:278988 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098989 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088990 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278991};
8992
[email protected]a13234c2012-03-20 21:45:028993static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018994#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028995 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8996 // have that ability on other platforms.
8997 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8998#else
8999 return 0;
9000#endif
9001}
9002
[email protected]3a86a712013-07-30 07:16:209003// SystemSupportsHardFailRevocationChecking returns true iff the current
9004// operating system supports revocation checking and can distinguish between
9005// situations where a given certificate lacks any revocation information (eg:
9006// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
9007// revocation information cannot be obtained (eg: the CRL was unreachable).
9008// If it does not, then tests which rely on 'hard fail' behaviour should be
9009// skipped.
9010static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:489011#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:209012 return true;
9013#else
9014 return false;
9015#endif
9016}
9017
[email protected]a13234c2012-03-20 21:45:029018// SystemUsesChromiumEVMetadata returns true iff the current operating system
9019// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
9020// several tests are effected because our testing EV certificate won't be
9021// recognised as EV.
9022static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:329023#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:579024 // http://crbug.com/117478 - OpenSSL does not support EV validation.
9025 return false;
[email protected]e1b2d732014-03-28 16:20:329026#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
9027 // On OS X and Android, we use the system to tell us whether a certificate is
9028 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:019029 return false;
9030#else
9031 return true;
9032#endif
9033}
9034
[email protected]b6f2de32012-08-17 04:35:089035static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:009036#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:579037 // http://crbug.com/117478 - OpenSSL does not support OCSP.
9038 return false;
9039#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:029040 return base::win::GetVersion() >= base::win::VERSION_VISTA;
9041#elif defined(OS_ANDROID)
9042 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
9043 return false;
9044#else
9045 return true;
9046#endif
9047}
9048
davidbend1fb2f12014-11-08 02:51:009049static bool SystemSupportsOCSPStapling() {
mathpc992e602015-10-21 20:34:039050#if defined(USE_NSS_CERTS) || defined(OS_IOS)
9051 return true;
9052#elif defined(OS_WIN)
9053 return base::win::GetVersion() >= base::win::VERSION_VISTA;
9054#else
9055 return false;
9056#endif
davidbend1fb2f12014-11-08 02:51:009057}
9058
[email protected]dffe8242012-03-20 15:14:279059TEST_F(HTTPSOCSPTest, Valid) {
9060 if (!SystemSupportsOCSP()) {
9061 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9062 return;
9063 }
9064
[email protected]ce7d0cbc2013-05-03 18:57:229065 SpawnedTestServer::SSLOptions ssl_options(
9066 SpawnedTestServer::SSLOptions::CERT_AUTO);
9067 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:279068
[email protected]924e9f92012-12-16 22:00:539069 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129070 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279071
9072 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9073
[email protected]a13234c2012-03-20 21:45:029074 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9075 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:279076
9077 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9078}
9079
9080TEST_F(HTTPSOCSPTest, Revoked) {
9081 if (!SystemSupportsOCSP()) {
9082 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9083 return;
9084 }
9085
[email protected]ce7d0cbc2013-05-03 18:57:229086 SpawnedTestServer::SSLOptions ssl_options(
9087 SpawnedTestServer::SSLOptions::CERT_AUTO);
9088 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:279089
9090 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129091 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279092
[email protected]a592c0432012-12-01 18:10:299093#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:279094 // Doesn't pass on OS X yet for reasons that need to be investigated.
9095 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9096#endif
9097 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9098 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9099}
9100
9101TEST_F(HTTPSOCSPTest, Invalid) {
9102 if (!SystemSupportsOCSP()) {
9103 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9104 return;
9105 }
9106
[email protected]ce7d0cbc2013-05-03 18:57:229107 SpawnedTestServer::SSLOptions ssl_options(
9108 SpawnedTestServer::SSLOptions::CERT_AUTO);
9109 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:279110
[email protected]924e9f92012-12-16 22:00:539111 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129112 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279113
[email protected]a13234c2012-03-20 21:45:029114 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:279115 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279116
9117 // Without a positive OCSP response, we shouldn't show the EV status.
9118 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9119 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9120}
[email protected]a13234c2012-03-20 21:45:029121
davidbend1fb2f12014-11-08 02:51:009122TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:039123 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009124 LOG(WARNING)
9125 << "Skipping test because system doesn't support OCSP stapling";
9126 return;
9127 }
9128
9129 SpawnedTestServer::SSLOptions ssl_options(
9130 SpawnedTestServer::SSLOptions::CERT_AUTO);
9131 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9132 ssl_options.staple_ocsp_response = true;
9133 ssl_options.ocsp_server_unavailable = true;
9134
9135 CertStatus cert_status;
9136 DoConnection(ssl_options, &cert_status);
9137
9138 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9139
9140 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9141 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9142
9143 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9144}
9145
davidben6c3191b2014-11-21 22:38:049146// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489147#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049148#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9149#else
9150#define MAYBE_RevokedStapled RevokedStapled
9151#endif
9152TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:039153 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009154 LOG(WARNING)
9155 << "Skipping test because system doesn't support OCSP stapling";
9156 return;
9157 }
9158
9159 SpawnedTestServer::SSLOptions ssl_options(
9160 SpawnedTestServer::SSLOptions::CERT_AUTO);
9161 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9162 ssl_options.staple_ocsp_response = true;
9163 ssl_options.ocsp_server_unavailable = true;
9164
9165 CertStatus cert_status;
9166 DoConnection(ssl_options, &cert_status);
9167
9168 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9169 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9170 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9171}
9172
[email protected]3a86a712013-07-30 07:16:209173class HTTPSHardFailTest : public HTTPSOCSPTest {
9174 protected:
dchengb03027d2014-10-21 12:00:209175 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:209176 context->set_ssl_config_service(
9177 new TestSSLConfigService(false /* check for EV */,
9178 false /* online revocation checking */,
9179 true /* require rev. checking for local
9180 anchors */));
9181 }
9182};
9183
[email protected]3a86a712013-07-30 07:16:209184TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
9185 if (!SystemSupportsOCSP()) {
9186 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9187 return;
9188 }
9189
9190 if (!SystemSupportsHardFailRevocationChecking()) {
9191 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
9192 << "revocation checking";
9193 return;
9194 }
9195
9196 SpawnedTestServer::SSLOptions ssl_options(
9197 SpawnedTestServer::SSLOptions::CERT_AUTO);
9198 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9199
9200 CertStatus cert_status;
9201 DoConnection(ssl_options, &cert_status);
9202
9203 EXPECT_EQ(CERT_STATUS_REVOKED,
9204 cert_status & CERT_STATUS_REVOKED);
9205
9206 // Without a positive OCSP response, we shouldn't show the EV status.
9207 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9208}
9209
[email protected]a13234c2012-03-20 21:45:029210class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
9211 protected:
dchengb03027d2014-10-21 12:00:209212 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:029213 context->set_ssl_config_service(
9214 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:209215 false /* online revocation checking */,
9216 false /* require rev. checking for local
9217 anchors */));
[email protected]a13234c2012-03-20 21:45:029218 }
9219};
9220
9221TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
9222 if (!SystemSupportsOCSP()) {
9223 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9224 return;
9225 }
9226
[email protected]ce7d0cbc2013-05-03 18:57:229227 SpawnedTestServer::SSLOptions ssl_options(
9228 SpawnedTestServer::SSLOptions::CERT_AUTO);
9229 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029230 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9231
[email protected]924e9f92012-12-16 22:00:539232 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129233 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029234
9235 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9236 cert_status & CERT_STATUS_ALL_ERRORS);
9237
9238 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089239 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9240 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029241}
9242
[email protected]be0fff62013-08-29 23:37:489243TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
9244 if (!SystemSupportsOCSP()) {
9245 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9246 return;
9247 }
9248
9249 SpawnedTestServer::SSLOptions ssl_options(
9250 SpawnedTestServer::SSLOptions::CERT_AUTO);
9251 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9252 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9253
9254 CertStatus cert_status;
9255 DoConnection(ssl_options, &cert_status);
9256
9257 // Currently only works for Windows. When using NSS or OS X, it's not
9258 // possible to determine whether the check failed because of actual
9259 // revocation or because there was an OCSP failure.
9260#if defined(OS_WIN)
9261 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9262#else
9263 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9264#endif
9265
9266 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9267 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9268 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9269}
9270
[email protected]a13234c2012-03-20 21:45:029271TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
9272 if (!SystemSupportsOCSP()) {
9273 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9274 return;
9275 }
9276
[email protected]ce7d0cbc2013-05-03 18:57:229277 SpawnedTestServer::SSLOptions ssl_options(
9278 SpawnedTestServer::SSLOptions::CERT_AUTO);
9279 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:029280 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9281
9282 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129283 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029284
9285 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9286
9287 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9288 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:089289 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9290 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029291}
9292
9293TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
9294 if (!SystemSupportsOCSP()) {
9295 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9296 return;
9297 }
9298
[email protected]ce7d0cbc2013-05-03 18:57:229299 SpawnedTestServer::SSLOptions ssl_options(
9300 SpawnedTestServer::SSLOptions::CERT_AUTO);
9301 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029302 SSLConfigService::SetCRLSet(
9303 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9304
9305 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129306 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029307
9308 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9309 cert_status & CERT_STATUS_ALL_ERRORS);
9310
9311 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089312 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9313 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029314}
9315
[email protected]51523f52013-07-31 21:57:289316TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9317 if (!SystemSupportsOCSP()) {
9318 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9319 return;
9320 }
9321
9322 SpawnedTestServer::SSLOptions ssl_options(
9323 SpawnedTestServer::SSLOptions::CERT_AUTO);
9324 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9325 SSLConfigService::SetCRLSet(
9326 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9327 false, &kOCSPTestCertSPKI, "")));
9328
9329 CertStatus cert_status;
9330 DoConnection(ssl_options, &cert_status);
9331
9332 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9333 // revocation check for EV.
9334 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9335 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9336 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9337 EXPECT_FALSE(
9338 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9339}
9340
9341TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9342 if (!SystemSupportsOCSP()) {
9343 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9344 return;
9345 }
9346
[email protected]ce7d0cbc2013-05-03 18:57:229347 SpawnedTestServer::SSLOptions ssl_options(
9348 SpawnedTestServer::SSLOptions::CERT_AUTO);
9349 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029350 SSLConfigService::SetCRLSet(
9351 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9352
[email protected]51523f52013-07-31 21:57:289353 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129354 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029355
[email protected]51523f52013-07-31 21:57:289356 // Even with a fresh CRLSet, we should still do online revocation checks when
9357 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9358 // test.
9359 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9360 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029361
[email protected]51523f52013-07-31 21:57:289362 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029363 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289364 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029365}
9366
[email protected]b6f2de32012-08-17 04:35:089367TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9368 // Test that when EV verification is requested, but online revocation
9369 // checking is disabled, and the leaf certificate is not in fact EV, that
9370 // no revocation checking actually happens.
9371 if (!SystemSupportsOCSP()) {
9372 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9373 return;
9374 }
9375
9376 // Unmark the certificate's OID as EV, which should disable revocation
9377 // checking (as per the user preference)
9378 ev_test_policy_.reset();
9379
[email protected]ce7d0cbc2013-05-03 18:57:229380 SpawnedTestServer::SSLOptions ssl_options(
9381 SpawnedTestServer::SSLOptions::CERT_AUTO);
9382 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089383 SSLConfigService::SetCRLSet(
9384 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9385
9386 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129387 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:089388
9389 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9390
9391 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9392 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9393}
9394
[email protected]a13234c2012-03-20 21:45:029395class HTTPSCRLSetTest : public HTTPSOCSPTest {
9396 protected:
dchengb03027d2014-10-21 12:00:209397 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:029398 context->set_ssl_config_service(
9399 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:209400 false /* online revocation checking */,
9401 false /* require rev. checking for local
9402 anchors */));
[email protected]a13234c2012-03-20 21:45:029403 }
9404};
9405
9406TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229407 SpawnedTestServer::SSLOptions ssl_options(
9408 SpawnedTestServer::SSLOptions::CERT_AUTO);
9409 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029410 SSLConfigService::SetCRLSet(
9411 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9412
[email protected]924e9f92012-12-16 22:00:539413 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129414 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029415
9416 // If we're not trying EV verification then, even if the CRLSet has expired,
9417 // we don't fall back to online revocation checks.
9418 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9419 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9420 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9421}
[email protected]51523f52013-07-31 21:57:289422
9423TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309424#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289425 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9426 return;
9427#endif
9428
9429 SpawnedTestServer::SSLOptions ssl_options(
9430 SpawnedTestServer::SSLOptions::CERT_AUTO);
9431 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9432 ssl_options.cert_serial = 10;
9433 SSLConfigService::SetCRLSet(
9434 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9435 false, &kOCSPTestCertSPKI, "\x0a")));
9436
9437 CertStatus cert_status = 0;
9438 DoConnection(ssl_options, &cert_status);
9439
9440 // If the certificate is recorded as revoked in the CRLSet, that should be
9441 // reflected without online revocation checking.
9442 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9443 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9444 EXPECT_FALSE(
9445 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9446}
[email protected]316c1e5e2012-09-12 15:17:449447#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279448
mmenke9f2ec60c2015-06-01 20:59:479449#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9450// These tests aren't passing on Android. Either the RemoteTestServer isn't
9451// starting up successfully, or it can't access the test files.
9452// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319453class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119454 public:
[email protected]d9fca99a2012-02-24 16:16:209455 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:479456 : ftp_transaction_factory_(&host_resolver_),
tommycli59a63432015-11-06 00:10:559457 ftp_test_server_(SpawnedTestServer::TYPE_FTP,
9458 SpawnedTestServer::kLocalhost,
9459 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:479460 // Can't use |default_context_|'s HostResolver to set up the
9461 // FTPTransactionFactory because it hasn't been created yet.
9462 default_context_.set_host_resolver(&host_resolver_);
9463 }
9464
9465 // URLRequestTest interface:
9466 void SetUpFactory() override {
9467 // Add FTP support to the default URLRequestContext.
9468 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:209469 "ftp",
9470 make_scoped_ptr(new FtpProtocolHandler(&ftp_transaction_factory_)));
mmenke9f2ec60c2015-06-01 20:59:479471 }
9472
9473 std::string GetTestFileContents() {
9474 base::FilePath path;
9475 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9476 path = path.Append(kTestFilePath);
9477 path = path.AppendASCII(kFtpTestFile);
9478 std::string contents;
9479 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9480 return contents;
[email protected]95409e12010-08-17 20:07:119481 }
9482
[email protected]b89ca032009-08-31 21:41:319483 protected:
mmenke9f2ec60c2015-06-01 20:59:479484 MockHostResolver host_resolver_;
9485 FtpNetworkLayer ftp_transaction_factory_;
9486
tommycli59a63432015-11-06 00:10:559487 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:319488};
9489
[email protected]d2a133182012-08-05 16:44:089490// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099491TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089492 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089493
9494 TestDelegate d;
9495 {
davidben151423e2015-03-23 18:48:369496 scoped_ptr<URLRequest> r(
9497 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199498 r->Start();
9499 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089500
[email protected]255620da2013-08-19 13:14:299501 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089502
[email protected]f7022f32014-08-21 16:32:199503 EXPECT_FALSE(r->is_pending());
9504 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
9505 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:089506 }
9507}
9508
mmenke9f2ec60c2015-06-01 20:59:479509TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:559510 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119511
[email protected]a25e90e2009-09-09 17:05:379512 TestDelegate d;
9513 {
[email protected]f7022f32014-08-21 16:32:199514 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559515 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199516 r->Start();
9517 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379518
[email protected]255620da2013-08-19 13:14:299519 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379520
[email protected]f7022f32014-08-21 16:32:199521 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379522 EXPECT_EQ(1, d.response_started_count());
9523 EXPECT_FALSE(d.received_data_before_response());
9524 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:559525 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199526 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559527 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199528 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379529 }
9530}
9531
mmenke9f2ec60c2015-06-01 20:59:479532TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:559533 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119534
[email protected]dd265012009-01-08 20:45:279535 TestDelegate d;
9536 {
[email protected]f7022f32014-08-21 16:32:199537 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559538 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199539 r->Start();
9540 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279541
[email protected]255620da2013-08-19 13:14:299542 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279543
[email protected]f7022f32014-08-21 16:32:199544 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279545 EXPECT_EQ(1, d.response_started_count());
9546 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479547 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559548 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199549 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559550 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199551 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279552 }
9553}
9554
mmenke9f2ec60c2015-06-01 20:59:479555TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:559556 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119557
[email protected]dd265012009-01-08 20:45:279558 TestDelegate d;
9559 {
tommycli59a63432015-11-06 00:10:559560 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9561 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9562 "chrome"),
9563 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199564 r->Start();
9565 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279566
[email protected]255620da2013-08-19 13:14:299567 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279568
[email protected]f7022f32014-08-21 16:32:199569 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479570 EXPECT_EQ(1, d.response_started_count());
9571 EXPECT_FALSE(d.received_data_before_response());
9572 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559573 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199574 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559575 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199576 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:259577
9578 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:199579 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:259580 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:279581 }
9582}
9583
mmenke9f2ec60c2015-06-01 20:59:479584TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:559585 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119586
[email protected]dd265012009-01-08 20:45:279587 TestDelegate d;
9588 {
[email protected]f7022f32014-08-21 16:32:199589 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559590 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9591 "wrong_password"),
davidben151423e2015-03-23 18:48:369592 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199593 r->Start();
9594 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279595
[email protected]255620da2013-08-19 13:14:299596 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279597
[email protected]f7022f32014-08-21 16:32:199598 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279599 EXPECT_EQ(1, d.response_started_count());
9600 EXPECT_FALSE(d.received_data_before_response());
9601 EXPECT_EQ(d.bytes_received(), 0);
9602 }
9603}
9604
mmenke9f2ec60c2015-06-01 20:59:479605TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:559606 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119607
[email protected]8b8a197d2009-08-26 15:57:589608 TestDelegate d;
9609 // Set correct login credentials. The delegate will be asked for them when
9610 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589611 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589612 {
[email protected]f7022f32014-08-21 16:32:199613 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559614 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9615 "wrong_password"),
davidben151423e2015-03-23 18:48:369616 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199617 r->Start();
9618 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589619
[email protected]255620da2013-08-19 13:14:299620 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589621
[email protected]f7022f32014-08-21 16:32:199622 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589623 EXPECT_EQ(1, d.response_started_count());
9624 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479625 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589626 }
9627}
9628
mmenke9f2ec60c2015-06-01 20:59:479629TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:559630 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119631
[email protected]dd265012009-01-08 20:45:279632 TestDelegate d;
9633 {
mmenke9f2ec60c2015-06-01 20:59:479634 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559635 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9636 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479637 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199638 r->Start();
9639 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279640
[email protected]255620da2013-08-19 13:14:299641 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279642
[email protected]f7022f32014-08-21 16:32:199643 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279644 EXPECT_EQ(1, d.response_started_count());
9645 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479646 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279647 }
9648}
[email protected]8b8a197d2009-08-26 15:57:589649
mmenke9f2ec60c2015-06-01 20:59:479650TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:559651 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119652
[email protected]8b8a197d2009-08-26 15:57:589653 TestDelegate d;
9654 // Set correct login credentials. The delegate will be asked for them when
9655 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589656 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589657 {
mmenke9f2ec60c2015-06-01 20:59:479658 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559659 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9660 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479661 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199662 r->Start();
9663 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589664
[email protected]255620da2013-08-19 13:14:299665 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589666
[email protected]f7022f32014-08-21 16:32:199667 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589668 EXPECT_EQ(1, d.response_started_count());
9669 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479670 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589671 }
9672}
[email protected]60a3df52009-09-22 16:13:249673
mmenke9f2ec60c2015-06-01 20:59:479674TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:559675 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119676
[email protected]60a3df52009-09-22 16:13:249677 scoped_ptr<TestDelegate> d(new TestDelegate);
9678 {
9679 // Pass correct login identity in the URL.
tommycli59a63432015-11-06 00:10:559680 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9681 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9682 "chrome"),
9683 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199684 r->Start();
9685 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249686
[email protected]255620da2013-08-19 13:14:299687 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249688
[email protected]f7022f32014-08-21 16:32:199689 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249690 EXPECT_EQ(1, d->response_started_count());
9691 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479692 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249693 }
9694
9695 d.reset(new TestDelegate);
9696 {
9697 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199698 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559699 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199700 r->Start();
9701 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249702
[email protected]255620da2013-08-19 13:14:299703 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249704
[email protected]f7022f32014-08-21 16:32:199705 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249706 EXPECT_EQ(1, d->response_started_count());
9707 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479708 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249709 }
9710}
9711
mmenke9f2ec60c2015-06-01 20:59:479712TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:559713 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119714
[email protected]60a3df52009-09-22 16:13:249715 scoped_ptr<TestDelegate> d(new TestDelegate);
9716 // Set correct login credentials. The delegate will be asked for them when
9717 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589718 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249719 {
[email protected]f7022f32014-08-21 16:32:199720 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559721 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9722 "wrong_password"),
davidben151423e2015-03-23 18:48:369723 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199724 r->Start();
9725 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249726
[email protected]255620da2013-08-19 13:14:299727 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249728
[email protected]f7022f32014-08-21 16:32:199729 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249730 EXPECT_EQ(1, d->response_started_count());
9731 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479732 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249733 }
9734
9735 // Use a new delegate without explicit credentials. The cached ones should be
9736 // used.
9737 d.reset(new TestDelegate);
9738 {
9739 // Don't pass wrong credentials in the URL, they would override valid cached
9740 // ones.
[email protected]f7022f32014-08-21 16:32:199741 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559742 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199743 r->Start();
9744 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249745
[email protected]255620da2013-08-19 13:14:299746 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249747
[email protected]f7022f32014-08-21 16:32:199748 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249749 EXPECT_EQ(1, d->response_started_count());
9750 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479751 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249752 }
9753}
[email protected]316c1e5e2012-09-12 15:17:449754#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519755
ttuttlec0c828492015-05-15 01:25:559756TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9757 TestDelegate d;
9758 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9759 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9760 d.set_quit_on_network_start(true);
9761
9762 EXPECT_FALSE(req->response_info().network_accessed);
9763
9764 req->Start();
9765 base::RunLoop().Run();
9766
9767 EXPECT_EQ(1, d.received_before_network_start_count());
9768 EXPECT_EQ(0, d.response_started_count());
9769 EXPECT_FALSE(req->response_info().network_accessed);
9770
9771 req->ResumeNetworkStart();
9772 base::RunLoop().Run();
9773}
9774
9775TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9776 TestDelegate d;
9777 scoped_ptr<URLRequest> req(
9778 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9779
9780 EXPECT_FALSE(req->response_info().network_accessed);
9781
9782 req->Start();
9783 base::RunLoop().Run();
9784
9785 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9786 EXPECT_FALSE(req->response_info().network_accessed);
9787}
9788
9789TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9790 MockHostResolver host_resolver;
9791 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9792 TestURLRequestContext context(true);
9793 context.set_network_delegate(&network_delegate);
9794 context.set_host_resolver(&host_resolver);
9795 host_resolver.rules()->AddSimulatedFailure("*");
9796 context.Init();
9797
9798 TestDelegate d;
9799 scoped_ptr<URLRequest> req(context.CreateRequest(
9800 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9801
9802 EXPECT_FALSE(req->response_info().network_accessed);
9803
9804 req->Start();
9805 base::RunLoop().Run();
9806 EXPECT_TRUE(req->response_info().network_accessed);
9807}
9808
mmenkeed0498b2015-12-08 23:20:429809// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:229810// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:429811TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:229812 TestDelegate d;
9813 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9814 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
9815
mmenkeed0498b2015-12-08 23:20:429816 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:229817 req.get(), &default_network_delegate_,
9818 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:429819 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
9820 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:229821
9822 req->Start();
9823 req->Cancel();
alexanderkcd904b52015-07-24 18:57:229824 base::RunLoop().RunUntilIdle();
9825 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
9826 EXPECT_EQ(0, d.received_redirect_count());
9827}
9828
[email protected]7461a402011-03-24 23:19:519829} // namespace net