blob: 435b21d0125a4ed612df21250e1b382813dc368c [file] [log] [blame]
[email protected]9045b8822012-01-13 20:35:351// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit586acc5fe2008-07-26 22:42:524
[email protected]ea224582008-12-07 20:25:465#include "build/build_config.h"
6
[email protected]9396b252008-09-29 17:29:387#if defined(OS_WIN)
[email protected]d8eb84242010-09-25 02:25:068#include <windows.h>
[email protected]aa84a7e2012-03-15 21:29:069#include <shlobj.h>
[email protected]9396b252008-09-29 17:29:3810#endif
11
tbansalea2fb8c2015-05-22 22:23:0012#include <stdint.h>
13
initial.commit586acc5fe2008-07-26 22:42:5214#include <algorithm>
initial.commit586acc5fe2008-07-26 22:42:5215
[email protected]aad63572011-05-24 20:14:3916#include "base/basictypes.h"
[email protected]218aa6a12011-09-13 17:38:3817#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5818#include "base/compiler_specific.h"
mmenke9f2ec60c2015-06-01 20:59:4719#include "base/files/file_path.h"
thestigd8df0332014-09-04 06:33:2920#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0721#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2822#include "base/format_macros.h"
estark06e0dac2015-08-07 21:56:0123#include "base/json/json_reader.h"
skyostil4891b25b2015-06-11 11:43:4524#include "base/location.h"
mmenke19378d22014-09-09 04:12:5925#include "base/memory/scoped_ptr.h"
[email protected]084262c2011-12-01 21:12:4726#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2227#include "base/message_loop/message_loop.h"
initial.commit586acc5fe2008-07-26 22:42:5228#include "base/path_service.h"
mmenkefb18c772015-09-30 22:22:5029#include "base/power_monitor/power_monitor.h"
30#include "base/power_monitor/power_monitor_source.h"
[email protected]255620da2013-08-19 13:14:2931#include "base/run_loop.h"
skyostil4891b25b2015-06-11 11:43:4532#include "base/single_thread_task_runner.h"
[email protected]4dc3ad4f2013-06-11 07:15:5033#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5534#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2235#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2236#include "base/strings/string_util.h"
37#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0538#include "base/strings/utf_string_conversions.h"
tbansalea2fb8c2015-05-22 22:23:0039#include "base/test/histogram_tester.h"
skyostil4891b25b2015-06-11 11:43:4540#include "base/thread_task_runner_handle.h"
estark06e0dac2015-08-07 21:56:0141#include "base/values.h"
mmenkecbc2b712014-10-09 20:29:0742#include "net/base/chunked_upload_data_stream.h"
43#include "net/base/elements_upload_data_stream.h"
tbansal1c92d5b2015-08-14 20:14:4344#include "net/base/external_estimate_provider.h"
initial.commit586acc5fe2008-07-26 22:42:5245#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2546#include "net/base/load_timing_info.h"
47#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0648#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5249#include "net/base/net_module.h"
50#include "net/base/net_util.h"
tbansalea2fb8c2015-05-22 22:23:0051#include "net/base/network_quality_estimator.h"
[email protected]2ca01e52013-10-31 22:05:1952#include "net/base/request_priority.h"
[email protected]42fdb452012-11-01 12:44:4053#include "net/base/test_data_directory.h"
[email protected]f288ef02012-12-15 20:28:2854#include "net/base/upload_bytes_element_reader.h"
55#include "net/base/upload_data_stream.h"
56#include "net/base/upload_file_element_reader.h"
[email protected]6e7845ae2013-03-29 21:48:1157#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2458#include "net/cert/mock_cert_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1159#include "net/cert/test_root_certs.h"
eromaned744f32015-04-09 06:35:4960#include "net/cert_net/nss_ocsp.h"
[email protected]aa84a7e2012-03-15 21:29:0661#include "net/cookies/cookie_monster.h"
62#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5263#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5364#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3865#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5266#include "net/http/http_cache.h"
67#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1968#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2569#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2170#include "net/http/http_response_headers.h"
[email protected]e50efea2014-03-24 18:41:0071#include "net/http/http_util.h"
eroman87c53d62015-04-02 06:51:0772#include "net/log/net_log.h"
vishal.b62985ca92015-04-17 08:45:5173#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4674#include "net/log/test_net_log_entry.h"
75#include "net/log/test_net_log_util.h"
[email protected]63de95b2008-12-10 04:11:2776#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1977#include "net/socket/ssl_client_socket.h"
davidben8ecc3072014-09-03 23:19:0978#include "net/ssl/ssl_cipher_suite_names.h"
[email protected]536fd0b2013-03-14 17:41:5779#include "net/ssl/ssl_connection_status_flags.h"
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
[email protected]71c64f62008-11-15 04:36:51285// Do a case-insensitive search through |haystack| for |needle|.
286bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50287 std::string::const_iterator it = std::search(
288 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
289 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51290 return it != haystack.end();
291}
292
mmenkecbc2b712014-10-09 20:29:07293scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
[email protected]f288ef02012-12-15 20:28:28294 scoped_ptr<UploadElementReader> reader(
295 new UploadBytesElementReader(data, strlen(data)));
mmenkecbc2b712014-10-09 20:29:07296 return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23297}
298
[email protected]96adadb2010-08-28 01:16:17299// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51300void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17301 // -1 means unknown. 0 means no encryption.
302 EXPECT_GT(ssl_info.security_bits, 0);
303
304 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
pkasting6b68a162014-12-01 22:10:29305 uint16 cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17306 ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29307 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17308}
309
[email protected]79e1fd62013-06-20 06:50:04310void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
311 const GURL& host_url) {
312 std::string sent_value;
313
314 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
315 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
316
317 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
318 EXPECT_EQ("keep-alive", sent_value);
319}
320
tommycli59a63432015-11-06 00:10:55321#if !defined(OS_IOS)
[email protected]ede03212012-09-07 12:52:26322bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27323 size_t size = a.size();
324
325 if (size != b.size())
326 return false;
327
328 for (size_t i = 0; i < size; ++i) {
329 if (!a[i].Equals(b[i]))
330 return false;
331 }
332
333 return true;
334}
[email protected]e3a85452013-11-14 01:46:17335#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27336
[email protected]dc5a5cf2012-09-26 02:49:30337// A network delegate that allows the user to choose a subset of request stages
338// to block in. When blocking, the delegate can do one of the following:
339// * synchronously return a pre-specified error code, or
340// * asynchronously return that value via an automatically called callback,
341// or
342// * block and wait for the user to do a callback.
343// Additionally, the user may also specify a redirect URL -- then each request
344// with the current URL different from the redirect target will be redirected
345// to that target, in the on-before-URL-request stage, independent of whether
346// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12347class BlockingNetworkDelegate : public TestNetworkDelegate {
348 public:
[email protected]dc5a5cf2012-09-26 02:49:30349 // Stages in which the delegate can block.
350 enum Stage {
[email protected]9045b8822012-01-13 20:35:35351 NOT_BLOCKED = 0,
352 ON_BEFORE_URL_REQUEST = 1 << 0,
353 ON_BEFORE_SEND_HEADERS = 1 << 1,
354 ON_HEADERS_RECEIVED = 1 << 2,
355 ON_AUTH_REQUIRED = 1 << 3
356 };
357
[email protected]dc5a5cf2012-09-26 02:49:30358 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59359 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30360 enum BlockMode {
361 SYNCHRONOUS, // No callback, returns specified return values.
362 AUTO_CALLBACK, // |this| posts a task to run the callback using the
363 // specified return codes.
364 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
365 // |auth_retval_| are ignored. In every blocking stage the
366 // message loop is quit.
367 };
368
369 // Creates a delegate which does not block at all.
370 explicit BlockingNetworkDelegate(BlockMode block_mode);
371
372 // For users to trigger a callback returning |response|.
373 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
374 // Only call if |block_mode_| == USER_CALLBACK.
375 void DoCallback(int response);
376 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
377
378 // Setters.
379 void set_retval(int retval) {
380 ASSERT_NE(USER_CALLBACK, block_mode_);
381 ASSERT_NE(ERR_IO_PENDING, retval);
382 ASSERT_NE(OK, retval);
383 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35384 }
385
[email protected]dc5a5cf2012-09-26 02:49:30386 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
387 // |auth_credentials_| will be passed with the response.
388 void set_auth_retval(AuthRequiredResponse auth_retval) {
389 ASSERT_NE(USER_CALLBACK, block_mode_);
390 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
391 auth_retval_ = auth_retval;
392 }
393 void set_auth_credentials(const AuthCredentials& auth_credentials) {
394 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35395 }
396
[email protected]dc5a5cf2012-09-26 02:49:30397 void set_redirect_url(const GURL& url) {
398 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35399 }
400
[email protected]dc5a5cf2012-09-26 02:49:30401 void set_block_on(int block_on) {
402 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35403 }
404
[email protected]dc5a5cf2012-09-26 02:49:30405 // Allows the user to check in which state did we block.
406 Stage stage_blocked_for_callback() const {
407 EXPECT_EQ(USER_CALLBACK, block_mode_);
408 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35409 }
410
411 private:
[email protected]dc5a5cf2012-09-26 02:49:30412 void RunCallback(int response, const CompletionCallback& callback);
413 void RunAuthCallback(AuthRequiredResponse response,
414 const AuthCallback& callback);
415
[email protected]9045b8822012-01-13 20:35:35416 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20417 int OnBeforeURLRequest(URLRequest* request,
418 const CompletionCallback& callback,
419 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35420
dchengb03027d2014-10-21 12:00:20421 int OnBeforeSendHeaders(URLRequest* request,
422 const CompletionCallback& callback,
423 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35424
dchengb03027d2014-10-21 12:00:20425 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35426 URLRequest* request,
427 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32428 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16429 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13430 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35431
dchengb03027d2014-10-21 12:00:20432 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35433 URLRequest* request,
434 const AuthChallengeInfo& auth_info,
435 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13436 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35437
[email protected]dc5a5cf2012-09-26 02:49:30438 // Resets the callbacks and |stage_blocked_for_callback_|.
439 void Reset();
[email protected]9045b8822012-01-13 20:35:35440
[email protected]dc5a5cf2012-09-26 02:49:30441 // Checks whether we should block in |stage|. If yes, returns an error code
442 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
443 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
444
445 // Configuration parameters, can be adjusted by public methods:
446 const BlockMode block_mode_;
447
448 // Values returned on blocking stages when mode is SYNCHRONOUS or
449 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
450 int retval_; // To be returned in non-auth stages.
451 AuthRequiredResponse auth_retval_;
452
[email protected]5f714132014-03-26 10:41:16453 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30454 int block_on_; // Bit mask: in which stages to block.
455
456 // |auth_credentials_| will be copied to |*target_auth_credential_| on
457 // callback.
458 AuthCredentials auth_credentials_;
459 AuthCredentials* target_auth_credentials_;
460
461 // Internal variables, not set by not the user:
462 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
463 // USER_CALLBACK).
464 Stage stage_blocked_for_callback_;
465
466 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35467 CompletionCallback callback_;
468 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30469
470 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
471
472 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35473};
474
[email protected]dc5a5cf2012-09-26 02:49:30475BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
476 : block_mode_(block_mode),
477 retval_(OK),
478 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
479 block_on_(0),
480 target_auth_credentials_(NULL),
481 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32482 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30483}
484
485void BlockingNetworkDelegate::DoCallback(int response) {
486 ASSERT_EQ(USER_CALLBACK, block_mode_);
487 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
488 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
489 CompletionCallback callback = callback_;
490 Reset();
491 RunCallback(response, callback);
492}
493
494void BlockingNetworkDelegate::DoAuthCallback(
495 NetworkDelegate::AuthRequiredResponse response) {
496 ASSERT_EQ(USER_CALLBACK, block_mode_);
497 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
498 AuthCallback auth_callback = auth_callback_;
499 Reset();
500 RunAuthCallback(response, auth_callback);
501}
502
503void BlockingNetworkDelegate::RunCallback(int response,
504 const CompletionCallback& callback) {
505 callback.Run(response);
506}
507
508void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
509 const AuthCallback& callback) {
510 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
511 ASSERT_TRUE(target_auth_credentials_ != NULL);
512 *target_auth_credentials_ = auth_credentials_;
513 }
514 callback.Run(response);
515}
516
517int BlockingNetworkDelegate::OnBeforeURLRequest(
518 URLRequest* request,
519 const CompletionCallback& callback,
520 GURL* new_url) {
521 if (redirect_url_ == request->url())
522 return OK; // We've already seen this request and redirected elsewhere.
523
524 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
525
526 if (!redirect_url_.is_empty())
527 *new_url = redirect_url_;
528
529 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
530}
531
532int BlockingNetworkDelegate::OnBeforeSendHeaders(
533 URLRequest* request,
534 const CompletionCallback& callback,
535 HttpRequestHeaders* headers) {
536 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
537
538 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
539}
540
541int BlockingNetworkDelegate::OnHeadersReceived(
542 URLRequest* request,
543 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32544 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16545 scoped_refptr<HttpResponseHeaders>* override_response_headers,
546 GURL* allowed_unsafe_redirect_url) {
547 TestNetworkDelegate::OnHeadersReceived(request,
548 callback,
549 original_response_headers,
550 override_response_headers,
551 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30552
553 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
554}
555
556NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
557 URLRequest* request,
558 const AuthChallengeInfo& auth_info,
559 const AuthCallback& callback,
560 AuthCredentials* credentials) {
561 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
562 credentials);
563 // Check that the user has provided callback for the previous blocked stage.
564 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
565
566 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
567 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
568 }
569
570 target_auth_credentials_ = credentials;
571
572 switch (block_mode_) {
573 case SYNCHRONOUS:
574 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
575 *target_auth_credentials_ = auth_credentials_;
576 return auth_retval_;
577
578 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45579 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30580 FROM_HERE,
581 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
582 weak_factory_.GetWeakPtr(), auth_retval_, callback));
583 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
584
585 case USER_CALLBACK:
586 auth_callback_ = callback;
587 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45588 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17589 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30590 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
591 }
592 NOTREACHED();
593 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
594}
595
596void BlockingNetworkDelegate::Reset() {
597 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
598 stage_blocked_for_callback_ = NOT_BLOCKED;
599 callback_.Reset();
600 auth_callback_.Reset();
601}
602
603int BlockingNetworkDelegate::MaybeBlockStage(
604 BlockingNetworkDelegate::Stage stage,
605 const CompletionCallback& callback) {
606 // Check that the user has provided callback for the previous blocked stage.
607 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
608
609 if ((block_on_ & stage) == 0) {
610 return OK;
611 }
612
613 switch (block_mode_) {
614 case SYNCHRONOUS:
615 EXPECT_NE(OK, retval_);
616 return retval_;
617
618 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45619 base::ThreadTaskRunnerHandle::Get()->PostTask(
620 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
621 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30622 return ERR_IO_PENDING;
623
624 case USER_CALLBACK:
625 callback_ = callback;
626 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45627 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17628 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30629 return ERR_IO_PENDING;
630 }
631 NOTREACHED();
632 return 0;
633}
634
[email protected]d5a4dd62012-05-23 01:41:04635class TestURLRequestContextWithProxy : public TestURLRequestContext {
636 public:
637 // Does not own |delegate|.
638 TestURLRequestContextWithProxy(const std::string& proxy,
639 NetworkDelegate* delegate)
640 : TestURLRequestContext(true) {
641 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
642 set_network_delegate(delegate);
643 Init();
644 }
dchengb03027d2014-10-21 12:00:20645 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04646};
647
estark06e0dac2015-08-07 21:56:01648// A mock ReportSender that just remembers the latest report
649// URI and report to be sent.
650class MockCertificateReportSender
651 : public TransportSecurityState::ReportSender {
652 public:
653 MockCertificateReportSender() {}
654 ~MockCertificateReportSender() override {}
655
656 void Send(const GURL& report_uri, const std::string& report) override {
657 latest_report_uri_ = report_uri;
658 latest_report_ = report;
659 }
660
661 const GURL& latest_report_uri() { return latest_report_uri_; }
662 const std::string& latest_report() { return latest_report_; }
663
664 private:
665 GURL latest_report_uri_;
666 std::string latest_report_;
667};
668
estarkcd39c11f2015-10-19 19:46:36669class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
670 public:
671 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
672};
673
[email protected]d5a4dd62012-05-23 01:41:04674} // namespace
675
[email protected]a592c0432012-12-01 18:10:29676// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48677class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00678 public:
[email protected]ef2bf422012-05-11 03:27:09679 URLRequestTest() : default_context_(true) {
680 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25681 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50682 job_factory_impl_ = new URLRequestJobFactoryImpl();
683 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50684 }
bengr1bf8e942014-11-07 01:36:50685
dcheng67be2b1f2014-10-27 21:47:29686 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18687 // URLRequestJobs may post clean-up tasks on destruction.
688 base::RunLoop().RunUntilIdle();
689 }
[email protected]87a09a92011-07-14 15:50:50690
dcheng2339883c2014-12-23 00:23:05691 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50692 SetUpFactory();
693 default_context_.set_job_factory(job_factory_.get());
694 default_context_.Init();
695 PlatformTest::SetUp();
696 }
697
698 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20699 job_factory_impl_->SetProtocolHandler(
700 "data", make_scoped_ptr(new DataProtocolHandler));
bengr1bf8e942014-11-07 01:36:50701#if !defined(DISABLE_FILE_SUPPORT)
702 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:20703 "file", make_scoped_ptr(new FileProtocolHandler(
704 base::ThreadTaskRunnerHandle::Get())));
bengr1bf8e942014-11-07 01:36:50705#endif
706 }
707
708 TestNetworkDelegate* default_network_delegate() {
709 return &default_network_delegate_;
710 }
711
712 const TestURLRequestContext& default_context() const {
713 return default_context_;
714 }
715
716
[email protected]3c5ca8c2011-09-29 01:14:51717 // Adds the TestJobInterceptor to the default context.
718 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23719 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20720 job_factory_impl_->SetProtocolHandler("http", nullptr);
721 job_factory_impl_->SetProtocolHandler("http",
722 make_scoped_ptr(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23723 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51724 }
725
[email protected]87a09a92011-07-14 15:50:50726 protected:
vishal.b62985ca92015-04-17 08:45:51727 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24728 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50729 URLRequestJobFactoryImpl* job_factory_impl_;
730 scoped_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09731 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48732};
733
[email protected]316c1e5e2012-09-12 15:17:44734TEST_F(URLRequestTest, AboutBlankTest) {
735 TestDelegate d;
736 {
[email protected]f7022f32014-08-21 16:32:19737 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36738 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44739
[email protected]f7022f32014-08-21 16:32:19740 r->Start();
741 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44742
[email protected]255620da2013-08-19 13:14:29743 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44744
[email protected]f7022f32014-08-21 16:32:19745 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44746 EXPECT_FALSE(d.received_data_before_response());
747 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19748 EXPECT_EQ("", r->GetSocketAddress().host());
749 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04750
751 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19752 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44753 }
754}
755
756TEST_F(URLRequestTest, DataURLImageTest) {
757 TestDelegate d;
758 {
759 // Use our nice little Chrome logo.
[email protected]f7022f32014-08-21 16:32:19760 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:19761 GURL(
davidben151423e2015-03-23 18:48:36762 "data:image/png;base64,"
763 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
764 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
765 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
766 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
767 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
768 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
769 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
770 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
771 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
772 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
773 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
774 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
775 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
776 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
777 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
778 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
779 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
780 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
781 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
782 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44783
[email protected]f7022f32014-08-21 16:32:19784 r->Start();
785 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44786
[email protected]255620da2013-08-19 13:14:29787 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44788
[email protected]f7022f32014-08-21 16:32:19789 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44790 EXPECT_FALSE(d.received_data_before_response());
791 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19792 EXPECT_EQ("", r->GetSocketAddress().host());
793 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04794
795 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19796 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44797 }
798}
799
[email protected]5ecf7cb282014-05-11 01:49:55800#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44801TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15802 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44803 PathService::Get(base::FILE_EXE, &app_path);
804 GURL app_url = FilePathToFileURL(app_path);
805
806 TestDelegate d;
807 {
davidben151423e2015-03-23 18:48:36808 scoped_ptr<URLRequest> r(
809 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44810
[email protected]f7022f32014-08-21 16:32:19811 r->Start();
812 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44813
[email protected]255620da2013-08-19 13:14:29814 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44815
816 int64 file_size = -1;
[email protected]56285702013-12-04 18:22:49817 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44818
[email protected]f7022f32014-08-21 16:32:19819 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44820 EXPECT_EQ(1, d.response_started_count());
821 EXPECT_FALSE(d.received_data_before_response());
822 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19823 EXPECT_EQ("", r->GetSocketAddress().host());
824 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04825
826 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19827 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44828 }
829}
830
[email protected]ba40bb762012-12-17 07:11:04831TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15832 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04833 PathService::Get(base::FILE_EXE, &app_path);
834 GURL app_url = FilePathToFileURL(app_path);
835
836 TestDelegate d;
837 {
davidben151423e2015-03-23 18:48:36838 scoped_ptr<URLRequest> r(
839 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04840
[email protected]f7022f32014-08-21 16:32:19841 r->Start();
842 EXPECT_TRUE(r->is_pending());
843 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04844 }
[email protected]79e1fd62013-06-20 06:50:04845 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04846 // destroyed.
[email protected]255620da2013-08-19 13:14:29847 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04848}
849
[email protected]316c1e5e2012-09-12 15:17:44850TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
851 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17852 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44853 FillBuffer(buffer.get(), buffer_size);
854
[email protected]6cdfd7f2013-02-08 20:40:15855 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52856 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44857 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30858 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44859
860 int64 file_size;
[email protected]56285702013-12-04 18:22:49861 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44862
863 const size_t first_byte_position = 500;
864 const size_t last_byte_position = buffer_size - first_byte_position;
865 const size_t content_length = last_byte_position - first_byte_position + 1;
866 std::string partial_buffer_string(buffer.get() + first_byte_position,
867 buffer.get() + last_byte_position + 1);
868
869 TestDelegate d;
870 {
davidben151423e2015-03-23 18:48:36871 scoped_ptr<URLRequest> r(
872 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44873
874 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38875 headers.SetHeader(
876 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59877 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38878 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19879 r->SetExtraRequestHeaders(headers);
880 r->Start();
881 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44882
[email protected]255620da2013-08-19 13:14:29883 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19884 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44885 EXPECT_EQ(1, d.response_started_count());
886 EXPECT_FALSE(d.received_data_before_response());
887 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
888 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
889 EXPECT_TRUE(partial_buffer_string == d.data_received());
890 }
891
[email protected]dd3aa792013-07-16 19:10:23892 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44893}
894
895TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
896 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17897 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44898 FillBuffer(buffer.get(), buffer_size);
899
[email protected]6cdfd7f2013-02-08 20:40:15900 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52901 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44902 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30903 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44904
905 int64 file_size;
[email protected]56285702013-12-04 18:22:49906 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44907
908 const size_t first_byte_position = 500;
909 const size_t last_byte_position = buffer_size - 1;
910 const size_t content_length = last_byte_position - first_byte_position + 1;
911 std::string partial_buffer_string(buffer.get() + first_byte_position,
912 buffer.get() + last_byte_position + 1);
913
914 TestDelegate d;
915 {
davidben151423e2015-03-23 18:48:36916 scoped_ptr<URLRequest> r(
917 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44918
919 HttpRequestHeaders headers;
920 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59921 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38922 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19923 r->SetExtraRequestHeaders(headers);
924 r->Start();
925 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44926
[email protected]255620da2013-08-19 13:14:29927 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19928 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44929 EXPECT_EQ(1, d.response_started_count());
930 EXPECT_FALSE(d.received_data_before_response());
931 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
932 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
933 EXPECT_TRUE(partial_buffer_string == d.data_received());
934 }
935
[email protected]dd3aa792013-07-16 19:10:23936 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44937}
938
939TEST_F(URLRequestTest, FileTestMultipleRanges) {
940 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17941 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44942 FillBuffer(buffer.get(), buffer_size);
943
[email protected]6cdfd7f2013-02-08 20:40:15944 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52945 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44946 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30947 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44948
949 int64 file_size;
[email protected]56285702013-12-04 18:22:49950 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44951
952 TestDelegate d;
953 {
davidben151423e2015-03-23 18:48:36954 scoped_ptr<URLRequest> r(
955 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44956
957 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38958 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19959 r->SetExtraRequestHeaders(headers);
960 r->Start();
961 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44962
[email protected]255620da2013-08-19 13:14:29963 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44964 EXPECT_TRUE(d.request_failed());
965 }
966
[email protected]dd3aa792013-07-16 19:10:23967 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44968}
969
[email protected]3ca8b362013-11-11 22:18:07970TEST_F(URLRequestTest, AllowFileURLs) {
971 base::ScopedTempDir temp_dir;
972 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
973 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52974 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07975 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:30976 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:59977 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:07978
979 {
980 TestDelegate d;
981 TestNetworkDelegate network_delegate;
982 network_delegate.set_can_access_files(true);
983 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36984 scoped_ptr<URLRequest> r(
985 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19986 r->Start();
[email protected]3ca8b362013-11-11 22:18:07987 base::RunLoop().Run();
988 EXPECT_FALSE(d.request_failed());
989 EXPECT_EQ(test_data, d.data_received());
990 }
991
992 {
993 TestDelegate d;
994 TestNetworkDelegate network_delegate;
995 network_delegate.set_can_access_files(false);
996 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36997 scoped_ptr<URLRequest> r(
998 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19999 r->Start();
[email protected]3ca8b362013-11-11 22:18:071000 base::RunLoop().Run();
1001 EXPECT_TRUE(d.request_failed());
1002 EXPECT_EQ("", d.data_received());
1003 }
1004}
1005
[email protected]316c1e5e2012-09-12 15:17:441006
1007TEST_F(URLRequestTest, FileDirCancelTest) {
1008 // Put in mock resource provider.
1009 NetModule::SetResourceProvider(TestNetResourceProvider);
1010
1011 TestDelegate d;
1012 {
[email protected]6cdfd7f2013-02-08 20:40:151013 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441014 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1015 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1016 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1017
[email protected]f7022f32014-08-21 16:32:191018 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361019 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191020 req->Start();
1021 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441022
1023 d.set_cancel_in_received_data_pending(true);
1024
[email protected]255620da2013-08-19 13:14:291025 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441026 }
1027
1028 // Take out mock resource provider.
1029 NetModule::SetResourceProvider(NULL);
1030}
1031
[email protected]5f9581402013-10-30 13:08:321032TEST_F(URLRequestTest, FileDirOutputSanity) {
1033 // Verify the general sanity of the the output of the file:
1034 // directory lister by checking for the output of a known existing
1035 // file.
1036 const char sentinel_name[] = "filedir-sentinel";
1037
1038 base::FilePath path;
1039 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471040 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321041
1042 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191043 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361044 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191045 req->Start();
[email protected]5f9581402013-10-30 13:08:321046 base::RunLoop().Run();
1047
1048 // Generate entry for the sentinel file.
1049 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581050 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491051 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321052 EXPECT_GT(info.size, 0);
1053 std::string sentinel_output = GetDirectoryListingEntry(
1054 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1055 std::string(sentinel_name),
1056 false /* is_dir */,
1057 info.size,
1058 info.last_modified);
1059
1060 ASSERT_LT(0, d.bytes_received());
1061 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191062 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:321063 // Check for the entry generated for the "sentinel" file.
1064 const std::string& data = d.data_received();
1065 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1066}
1067
[email protected]316c1e5e2012-09-12 15:17:441068TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1069 // There is an implicit redirect when loading a file path that matches a
1070 // directory and does not end with a slash. Ensure that following such
1071 // redirects does not crash. See http://crbug.com/18686.
1072
[email protected]6cdfd7f2013-02-08 20:40:151073 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441074 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471075 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441076
1077 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191078 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361079 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191080 req->Start();
[email protected]255620da2013-08-19 13:14:291081 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441082
1083 ASSERT_EQ(1, d.received_redirect_count());
1084 ASSERT_LT(0, d.bytes_received());
1085 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191086 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441087}
1088
1089#if defined(OS_WIN)
1090// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1091TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1092 TestDelegate d;
davidben151423e2015-03-23 18:48:361093 scoped_ptr<URLRequest> req(
1094 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191095 req->Start();
[email protected]255620da2013-08-19 13:14:291096 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441097
1098 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191099 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441100}
[email protected]5ecf7cb282014-05-11 01:49:551101#endif // defined(OS_WIN)
1102
1103#endif // !defined(DISABLE_FILE_SUPPORT)
1104
1105TEST_F(URLRequestTest, InvalidUrlTest) {
1106 TestDelegate d;
1107 {
[email protected]f7022f32014-08-21 16:32:191108 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361109 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551110
[email protected]f7022f32014-08-21 16:32:191111 r->Start();
1112 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551113
1114 base::RunLoop().Run();
1115 EXPECT_TRUE(d.request_failed());
1116 }
1117}
1118
jochen0e3b3a62014-09-16 18:31:231119TEST_F(URLRequestTest, InvalidReferrerTest) {
1120 TestURLRequestContext context;
1121 TestNetworkDelegate network_delegate;
1122 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1123 context.set_network_delegate(&network_delegate);
1124 TestDelegate d;
davidben151423e2015-03-23 18:48:361125 scoped_ptr<URLRequest> req(
1126 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231127 req->SetReferrer("https://somewhere.com/");
1128
1129 req->Start();
1130 base::RunLoop().Run();
1131 EXPECT_TRUE(d.request_failed());
1132}
1133
[email protected]5ecf7cb282014-05-11 01:49:551134#if defined(OS_WIN)
1135TEST_F(URLRequestTest, ResolveShortcutTest) {
1136 base::FilePath app_path;
1137 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471138 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551139 app_path = app_path.AppendASCII("with-headers.html");
1140
1141 std::wstring lnk_path = app_path.value() + L".lnk";
1142
1143 base::win::ScopedCOMInitializer com_initializer;
1144
1145 // Temporarily create a shortcut for test
1146 {
1147 base::win::ScopedComPtr<IShellLink> shell;
1148 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1149 CLSCTX_INPROC_SERVER)));
1150 base::win::ScopedComPtr<IPersistFile> persist;
1151 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1152 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1153 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1154 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1155 }
1156
1157 TestDelegate d;
1158 {
[email protected]f7022f32014-08-21 16:32:191159 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361160 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551161
[email protected]f7022f32014-08-21 16:32:191162 r->Start();
1163 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551164
1165 base::RunLoop().Run();
1166
1167 WIN32_FILE_ATTRIBUTE_DATA data;
1168 GetFileAttributesEx(app_path.value().c_str(),
1169 GetFileExInfoStandard, &data);
1170 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1171 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1172 FILE_ATTRIBUTE_NORMAL, NULL);
1173 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1174 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1175 DWORD read_size;
1176 BOOL result;
1177 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1178 &read_size, NULL);
1179 std::string content(buffer.get(), read_size);
1180 CloseHandle(file);
1181
[email protected]f7022f32014-08-21 16:32:191182 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551183 EXPECT_EQ(1, d.received_redirect_count());
1184 EXPECT_EQ(content, d.data_received());
1185 }
1186
1187 // Clean the shortcut
1188 DeleteFile(lnk_path.c_str());
1189}
1190#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441191
1192// Custom URLRequestJobs for use with interceptor tests
1193class RestartTestJob : public URLRequestTestJob {
1194 public:
1195 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1196 : URLRequestTestJob(request, network_delegate, true) {}
1197 protected:
dchengb03027d2014-10-21 12:00:201198 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441199 private:
dchengb03027d2014-10-21 12:00:201200 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441201};
1202
1203class CancelTestJob : public URLRequestTestJob {
1204 public:
1205 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1206 : URLRequestTestJob(request, network_delegate, true) {}
1207 protected:
dchengb03027d2014-10-21 12:00:201208 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441209 private:
dchengb03027d2014-10-21 12:00:201210 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441211};
1212
1213class CancelThenRestartTestJob : public URLRequestTestJob {
1214 public:
1215 explicit CancelThenRestartTestJob(URLRequest* request,
1216 NetworkDelegate* network_delegate)
1217 : URLRequestTestJob(request, network_delegate, true) {
1218 }
1219 protected:
dchengb03027d2014-10-21 12:00:201220 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441221 request_->Cancel();
1222 this->NotifyRestartRequired();
1223 }
1224 private:
dchengb03027d2014-10-21 12:00:201225 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441226};
1227
bengr1bf8e942014-11-07 01:36:501228// An Interceptor for use with interceptor tests.
1229class MockURLRequestInterceptor : public URLRequestInterceptor {
1230 public:
1231 // Static getters for canned response header and data strings.
1232 static std::string ok_data() {
1233 return URLRequestTestJob::test_data_1();
1234 }
1235
1236 static std::string ok_headers() {
1237 return URLRequestTestJob::test_headers();
1238 }
1239
1240 static std::string redirect_data() {
1241 return std::string();
1242 }
1243
1244 static std::string redirect_headers() {
1245 return URLRequestTestJob::test_redirect_headers();
1246 }
1247
1248 static std::string error_data() {
1249 return std::string("ohhh nooooo mr. bill!");
1250 }
1251
1252 static std::string error_headers() {
1253 return URLRequestTestJob::test_error_headers();
1254 }
1255
1256 MockURLRequestInterceptor()
1257 : intercept_main_request_(false), restart_main_request_(false),
1258 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1259 simulate_main_network_error_(false),
1260 intercept_redirect_(false), cancel_redirect_request_(false),
1261 intercept_final_response_(false), cancel_final_request_(false),
1262 use_url_request_http_job_(false),
1263 did_intercept_main_(false), did_restart_main_(false),
1264 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1265 did_simulate_error_main_(false),
1266 did_intercept_redirect_(false), did_cancel_redirect_(false),
1267 did_intercept_final_(false), did_cancel_final_(false) {
1268 }
1269
1270 ~MockURLRequestInterceptor() override {
1271 }
1272
1273 // URLRequestInterceptor implementation:
1274 URLRequestJob* MaybeInterceptRequest(
1275 URLRequest* request,
1276 NetworkDelegate* network_delegate) const override {
1277 if (restart_main_request_) {
1278 restart_main_request_ = false;
1279 did_restart_main_ = true;
1280 return new RestartTestJob(request, network_delegate);
1281 }
1282 if (cancel_main_request_) {
1283 cancel_main_request_ = false;
1284 did_cancel_main_ = true;
1285 return new CancelTestJob(request, network_delegate);
1286 }
1287 if (cancel_then_restart_main_request_) {
1288 cancel_then_restart_main_request_ = false;
1289 did_cancel_then_restart_main_ = true;
1290 return new CancelThenRestartTestJob(request, network_delegate);
1291 }
1292 if (simulate_main_network_error_) {
1293 simulate_main_network_error_ = false;
1294 did_simulate_error_main_ = true;
1295 if (use_url_request_http_job_) {
1296 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1297 }
1298 // This job will result in error since the requested URL is not one of the
1299 // URLs supported by these tests.
1300 return new URLRequestTestJob(request, network_delegate, true);
1301 }
1302 if (!intercept_main_request_)
1303 return nullptr;
1304 intercept_main_request_ = false;
1305 did_intercept_main_ = true;
1306 URLRequestTestJob* job = new URLRequestTestJob(request,
1307 network_delegate,
1308 main_headers_,
1309 main_data_,
1310 true);
1311 job->set_load_timing_info(main_request_load_timing_info_);
1312 return job;
1313 }
1314
1315 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1316 NetworkDelegate* network_delegate,
1317 const GURL& location) const override {
1318 if (cancel_redirect_request_) {
1319 cancel_redirect_request_ = false;
1320 did_cancel_redirect_ = true;
1321 return new CancelTestJob(request, network_delegate);
1322 }
1323 if (!intercept_redirect_)
1324 return nullptr;
1325 intercept_redirect_ = false;
1326 did_intercept_redirect_ = true;
1327 if (use_url_request_http_job_) {
1328 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1329 }
1330 return new URLRequestTestJob(request,
1331 network_delegate,
1332 redirect_headers_,
1333 redirect_data_,
1334 true);
1335 }
1336
1337 URLRequestJob* MaybeInterceptResponse(
1338 URLRequest* request,
1339 NetworkDelegate* network_delegate) const override {
1340 if (cancel_final_request_) {
1341 cancel_final_request_ = false;
1342 did_cancel_final_ = true;
1343 return new CancelTestJob(request, network_delegate);
1344 }
1345 if (!intercept_final_response_)
1346 return nullptr;
1347 intercept_final_response_ = false;
1348 did_intercept_final_ = 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 final_headers_,
1355 final_data_,
1356 true);
1357 }
1358
1359 void set_intercept_main_request(bool intercept_main_request) {
1360 intercept_main_request_ = intercept_main_request;
1361 }
1362
1363 void set_main_headers(const std::string& main_headers) {
1364 main_headers_ = main_headers;
1365 }
1366
1367 void set_main_data(const std::string& main_data) {
1368 main_data_ = main_data;
1369 }
1370
1371 void set_main_request_load_timing_info(
1372 const LoadTimingInfo& main_request_load_timing_info) {
1373 main_request_load_timing_info_ = main_request_load_timing_info;
1374 }
1375
1376 void set_restart_main_request(bool restart_main_request) {
1377 restart_main_request_ = restart_main_request;
1378 }
1379
1380 void set_cancel_main_request(bool cancel_main_request) {
1381 cancel_main_request_ = cancel_main_request;
1382 }
1383
1384 void set_cancel_then_restart_main_request(
1385 bool cancel_then_restart_main_request) {
1386 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1387 }
1388
1389 void set_simulate_main_network_error(bool simulate_main_network_error) {
1390 simulate_main_network_error_ = simulate_main_network_error;
1391 }
1392
1393 void set_intercept_redirect(bool intercept_redirect) {
1394 intercept_redirect_ = intercept_redirect;
1395 }
1396
1397 void set_redirect_headers(const std::string& redirect_headers) {
1398 redirect_headers_ = redirect_headers;
1399 }
1400
1401 void set_redirect_data(const std::string& redirect_data) {
1402 redirect_data_ = redirect_data;
1403 }
1404
1405 void set_cancel_redirect_request(bool cancel_redirect_request) {
1406 cancel_redirect_request_ = cancel_redirect_request;
1407 }
1408
1409 void set_intercept_final_response(bool intercept_final_response) {
1410 intercept_final_response_ = intercept_final_response;
1411 }
1412
1413 void set_final_headers(const std::string& final_headers) {
1414 final_headers_ = final_headers;
1415 }
1416
1417 void set_final_data(const std::string& final_data) {
1418 final_data_ = final_data;
1419 }
1420
1421 void set_cancel_final_request(bool cancel_final_request) {
1422 cancel_final_request_ = cancel_final_request;
1423 }
1424
1425 void set_use_url_request_http_job(bool use_url_request_http_job) {
1426 use_url_request_http_job_ = use_url_request_http_job;
1427 }
1428
1429 bool did_intercept_main() const {
1430 return did_intercept_main_;
1431 }
1432
1433 bool did_restart_main() const {
1434 return did_restart_main_;
1435 }
1436
1437 bool did_cancel_main() const {
1438 return did_cancel_main_;
1439 }
1440
1441 bool did_cancel_then_restart_main() const {
1442 return did_cancel_then_restart_main_;
1443 }
1444
1445 bool did_simulate_error_main() const {
1446 return did_simulate_error_main_;
1447 }
1448
1449 bool did_intercept_redirect() const {
1450 return did_intercept_redirect_;
1451 }
1452
1453 bool did_cancel_redirect() const {
1454 return did_cancel_redirect_;
1455 }
1456
1457 bool did_intercept_final() const {
1458 return did_intercept_final_;
1459 }
1460
1461 bool did_cancel_final() const {
1462 return did_cancel_final_;
1463 }
1464
1465 private:
1466 // Indicate whether to intercept the main request, and if so specify the
1467 // response to return and the LoadTimingInfo to use.
1468 mutable bool intercept_main_request_;
1469 mutable std::string main_headers_;
1470 mutable std::string main_data_;
1471 mutable LoadTimingInfo main_request_load_timing_info_;
1472
1473 // These indicate actions that can be taken within MaybeInterceptRequest.
1474 mutable bool restart_main_request_;
1475 mutable bool cancel_main_request_;
1476 mutable bool cancel_then_restart_main_request_;
1477 mutable bool simulate_main_network_error_;
1478
1479 // Indicate whether to intercept redirects, and if so specify the response to
1480 // return.
1481 mutable bool intercept_redirect_;
1482 mutable std::string redirect_headers_;
1483 mutable std::string redirect_data_;
1484
1485 // Cancel the request within MaybeInterceptRedirect.
1486 mutable bool cancel_redirect_request_;
1487
1488 // Indicate whether to intercept the final response, and if so specify the
1489 // response to return.
1490 mutable bool intercept_final_response_;
1491 mutable std::string final_headers_;
1492 mutable std::string final_data_;
1493
1494 // Cancel the final request within MaybeInterceptResponse.
1495 mutable bool cancel_final_request_;
1496
1497 // Instruct the interceptor to use a real URLRequestHTTPJob.
1498 mutable bool use_url_request_http_job_;
1499
1500 // These indicate if the interceptor did something or not.
1501 mutable bool did_intercept_main_;
1502 mutable bool did_restart_main_;
1503 mutable bool did_cancel_main_;
1504 mutable bool did_cancel_then_restart_main_;
1505 mutable bool did_simulate_error_main_;
1506 mutable bool did_intercept_redirect_;
1507 mutable bool did_cancel_redirect_;
1508 mutable bool did_intercept_final_;
1509 mutable bool did_cancel_final_;
1510};
1511
1512// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1513class URLRequestInterceptorTest : public URLRequestTest {
1514 public:
1515 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1516 }
1517
1518 ~URLRequestInterceptorTest() override {
1519 // URLRequestJobs may post clean-up tasks on destruction.
1520 base::RunLoop().RunUntilIdle();
1521 }
1522
1523 void SetUpFactory() override {
1524 interceptor_ = new MockURLRequestInterceptor();
1525 job_factory_.reset(new URLRequestInterceptingJobFactory(
1526 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1527 }
1528
1529 MockURLRequestInterceptor* interceptor() const {
1530 return interceptor_;
1531 }
1532
1533 private:
1534 MockURLRequestInterceptor* interceptor_;
1535};
1536
1537TEST_F(URLRequestInterceptorTest, Intercept) {
1538 // Intercept the main request and respond with a simple response.
1539 interceptor()->set_intercept_main_request(true);
1540 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1541 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591542 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501543 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361544 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501545 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1546 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1547 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1548 req->SetUserData(nullptr, user_data0);
1549 req->SetUserData(&user_data1, user_data1);
1550 req->SetUserData(&user_data2, user_data2);
1551 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191552 req->Start();
[email protected]255620da2013-08-19 13:14:291553 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591554
bengr1bf8e942014-11-07 01:36:501555 // Make sure we can retrieve our specific user data.
1556 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1557 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1558 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591559
bengr1bf8e942014-11-07 01:36:501560 // Check that we got one good response.
1561 EXPECT_TRUE(req->status().is_success());
1562 EXPECT_EQ(200, req->response_headers()->response_code());
1563 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1564 EXPECT_EQ(1, d.response_started_count());
1565 EXPECT_EQ(0, d.received_redirect_count());
1566}
[email protected]2bba3252013-04-08 19:50:591567
bengr1bf8e942014-11-07 01:36:501568TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1569 // Intercept the main request and respond with a redirect.
1570 interceptor()->set_intercept_main_request(true);
1571 interceptor()->set_main_headers(
1572 MockURLRequestInterceptor::redirect_headers());
1573 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1574
1575 // Intercept that redirect and respond with a final OK response.
1576 interceptor()->set_intercept_redirect(true);
1577 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1578 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1579
1580 TestDelegate d;
1581 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361582 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501583 req->set_method("GET");
1584 req->Start();
1585 base::RunLoop().Run();
1586
1587 // Check that the interceptor got called as expected.
1588 EXPECT_TRUE(interceptor()->did_intercept_main());
1589 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1590
1591 // Check that we got one good response.
1592 EXPECT_TRUE(req->status().is_success());
1593 if (req->status().is_success())
1594 EXPECT_EQ(200, req->response_headers()->response_code());
1595
1596 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1597 EXPECT_EQ(1, d.response_started_count());
1598 EXPECT_EQ(0, d.received_redirect_count());
1599}
1600
1601TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1602 // Intercept the main request to generate a server error response.
1603 interceptor()->set_intercept_main_request(true);
1604 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1605 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1606
1607 // Intercept that error and respond with an OK response.
1608 interceptor()->set_intercept_final_response(true);
1609 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1610 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1611
1612 TestDelegate d;
1613 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361614 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501615 req->set_method("GET");
1616 req->Start();
1617 base::RunLoop().Run();
1618
1619 // Check that the interceptor got called as expected.
1620 EXPECT_TRUE(interceptor()->did_intercept_main());
1621 EXPECT_TRUE(interceptor()->did_intercept_final());
1622
1623 // Check that we got one good response.
1624 EXPECT_TRUE(req->status().is_success());
1625 EXPECT_EQ(200, req->response_headers()->response_code());
1626 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1627 EXPECT_EQ(1, d.response_started_count());
1628 EXPECT_EQ(0, d.received_redirect_count());
1629}
1630
1631TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1632 // Intercept the main request to simulate a network error.
1633 interceptor()->set_simulate_main_network_error(true);
1634
1635 // Intercept that error and respond with an OK response.
1636 interceptor()->set_intercept_final_response(true);
1637 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1638 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1639
1640 TestDelegate d;
1641 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361642 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501643 req->set_method("GET");
1644 req->Start();
1645 base::RunLoop().Run();
1646
1647 // Check that the interceptor got called as expected.
1648 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1649 EXPECT_TRUE(interceptor()->did_intercept_final());
1650
1651 // Check that we received one good response.
1652 EXPECT_TRUE(req->status().is_success());
1653 EXPECT_EQ(200, req->response_headers()->response_code());
1654 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1655 EXPECT_EQ(1, d.response_started_count());
1656 EXPECT_EQ(0, d.received_redirect_count());
1657}
1658
1659TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1660 // Restart the main request.
1661 interceptor()->set_restart_main_request(true);
1662
1663 // then intercept the new main request and respond with an OK response
1664 interceptor()->set_intercept_main_request(true);
1665 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1666 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1667
1668 TestDelegate d;
1669 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361670 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501671 req->set_method("GET");
1672 req->Start();
1673 base::RunLoop().Run();
1674
1675 // Check that the interceptor got called as expected.
1676 EXPECT_TRUE(interceptor()->did_restart_main());
1677 EXPECT_TRUE(interceptor()->did_intercept_main());
1678
1679 // Check that we received one good response.
1680 EXPECT_TRUE(req->status().is_success());
1681 if (req->status().is_success())
1682 EXPECT_EQ(200, req->response_headers()->response_code());
1683
1684 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1685 EXPECT_EQ(1, d.response_started_count());
1686 EXPECT_EQ(0, d.received_redirect_count());
1687}
1688
1689TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1690 // Intercept the main request and cancel from within the restarted job.
1691 interceptor()->set_cancel_main_request(true);
1692
1693 // Set up to intercept the final response and override it with an OK response.
1694 interceptor()->set_intercept_final_response(true);
1695 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1696 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1697
1698 TestDelegate d;
1699 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361700 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501701 req->set_method("GET");
1702 req->Start();
1703 base::RunLoop().Run();
1704
1705 // Check that the interceptor got called as expected.
1706 EXPECT_TRUE(interceptor()->did_cancel_main());
1707 EXPECT_FALSE(interceptor()->did_intercept_final());
1708
1709 // Check that we see a canceled request.
1710 EXPECT_FALSE(req->status().is_success());
1711 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1712}
1713
1714TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1715 // Intercept the main request and respond with a redirect.
1716 interceptor()->set_intercept_main_request(true);
1717 interceptor()->set_main_headers(
1718 MockURLRequestInterceptor::redirect_headers());
1719 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1720
1721 // Intercept the redirect and cancel from within that job.
1722 interceptor()->set_cancel_redirect_request(true);
1723
1724 // Set up to intercept the final response and override it with an OK response.
1725 interceptor()->set_intercept_final_response(true);
1726 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1727 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1728
1729 TestDelegate d;
1730 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361731 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501732 req->set_method("GET");
1733 req->Start();
1734 base::RunLoop().Run();
1735
1736 // Check that the interceptor got called as expected.
1737 EXPECT_TRUE(interceptor()->did_intercept_main());
1738 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1739 EXPECT_FALSE(interceptor()->did_intercept_final());
1740
1741 // Check that we see a canceled request.
1742 EXPECT_FALSE(req->status().is_success());
1743 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1744}
1745
1746TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1747 // Intercept the main request to simulate a network error.
1748 interceptor()->set_simulate_main_network_error(true);
1749
1750 // Set up to intercept final the response and cancel from within that job.
1751 interceptor()->set_cancel_final_request(true);
1752
1753 TestDelegate d;
1754 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361755 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501756 req->set_method("GET");
1757 req->Start();
1758 base::RunLoop().Run();
1759
1760 // Check that the interceptor got called as expected.
1761 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1762 EXPECT_TRUE(interceptor()->did_cancel_final());
1763
1764 // Check that we see a canceled request.
1765 EXPECT_FALSE(req->status().is_success());
1766 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1767}
1768
1769TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1770 // Intercept the main request and cancel then restart from within that job.
1771 interceptor()->set_cancel_then_restart_main_request(true);
1772
1773 // Set up to intercept the final response and override it with an OK response.
1774 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501775 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1776 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501777
1778 TestDelegate d;
1779 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361780 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501781 req->set_method("GET");
1782 req->Start();
1783 base::RunLoop().Run();
1784
1785 // Check that the interceptor got called as expected.
1786 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1787 EXPECT_FALSE(interceptor()->did_intercept_final());
1788
1789 // Check that we see a canceled request.
1790 EXPECT_FALSE(req->status().is_success());
1791 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591792}
1793
1794// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1795// reused. |connect_time_flags| is used to indicate if there should be dns
1796// or SSL times, and |used_proxy| is used for proxy times.
1797LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1798 int connect_time_flags,
1799 bool used_proxy) {
1800 LoadTimingInfo load_timing;
1801 load_timing.socket_log_id = 1;
1802
1803 if (used_proxy) {
1804 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1805 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1806 }
1807
1808 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1809 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1810 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1811 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1812 }
1813 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1814 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1815 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1816 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1817 }
1818 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1819
1820 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1821 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1822 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1823 return load_timing;
1824}
1825
1826// Same as above, but in the case of a reused socket.
1827LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1828 bool used_proxy) {
1829 LoadTimingInfo load_timing;
1830 load_timing.socket_log_id = 1;
1831 load_timing.socket_reused = true;
1832
1833 if (used_proxy) {
1834 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1835 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1836 }
1837
1838 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1839 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1840 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1841 return load_timing;
1842}
1843
bengr1bf8e942014-11-07 01:36:501844LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1845 const LoadTimingInfo& job_load_timing,
1846 const URLRequestContext& context,
1847 MockURLRequestInterceptor* interceptor) {
1848 interceptor->set_intercept_main_request(true);
1849 interceptor->set_main_request_load_timing_info(job_load_timing);
1850 TestDelegate d;
1851 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361852 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501853 req->Start();
1854 base::RunLoop().Run();
1855
1856 LoadTimingInfo resulting_load_timing;
1857 req->GetLoadTimingInfo(&resulting_load_timing);
1858
1859 // None of these should be modified by the URLRequest.
1860 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1861 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1862 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1863 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1864 EXPECT_EQ(job_load_timing.receive_headers_end,
1865 resulting_load_timing.receive_headers_end);
1866
1867 return resulting_load_timing;
1868}
1869
[email protected]2bba3252013-04-08 19:50:591870// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501871TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591872 base::TimeTicks now = base::TimeTicks::Now();
1873 LoadTimingInfo job_load_timing =
1874 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1875
[email protected]2ca01e52013-10-31 22:05:191876 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501877 RunURLRequestInterceptorLoadTimingTest(
1878 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591879
1880 // Nothing should have been changed by the URLRequest.
1881 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1882 load_timing_result.proxy_resolve_start);
1883 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1884 load_timing_result.proxy_resolve_end);
1885 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1886 load_timing_result.connect_timing.dns_start);
1887 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1888 load_timing_result.connect_timing.dns_end);
1889 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1890 load_timing_result.connect_timing.connect_start);
1891 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1892 load_timing_result.connect_timing.connect_end);
1893 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1894 load_timing_result.connect_timing.ssl_start);
1895 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1896 load_timing_result.connect_timing.ssl_end);
1897
1898 // Redundant sanity check.
1899 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1900}
1901
1902// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501903TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591904 base::TimeTicks now = base::TimeTicks::Now();
1905 LoadTimingInfo job_load_timing =
1906 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1907
[email protected]2ca01e52013-10-31 22:05:191908 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501909 RunURLRequestInterceptorLoadTimingTest(
1910 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591911
1912 // Nothing should have been changed by the URLRequest.
1913 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1914 load_timing_result.proxy_resolve_start);
1915 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1916 load_timing_result.proxy_resolve_end);
1917 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1918 load_timing_result.connect_timing.dns_start);
1919 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1920 load_timing_result.connect_timing.dns_end);
1921 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1922 load_timing_result.connect_timing.connect_start);
1923 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1924 load_timing_result.connect_timing.connect_end);
1925 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1926 load_timing_result.connect_timing.ssl_start);
1927 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1928 load_timing_result.connect_timing.ssl_end);
1929
1930 // Redundant sanity check.
1931 TestLoadTimingNotReusedWithProxy(load_timing_result,
1932 CONNECT_TIMING_HAS_SSL_TIMES);
1933}
1934
1935// Make sure that URLRequest correctly adjusts proxy times when they're before
1936// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101937// the case of reusing a SPDY session. The connected socket is not considered
1938// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591939//
1940// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501941TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591942 base::TimeTicks now = base::TimeTicks::Now();
1943 LoadTimingInfo job_load_timing =
1944 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1945 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1946 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1947 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1948 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1949 job_load_timing.connect_timing.connect_start =
1950 now - base::TimeDelta::FromDays(2);
1951 job_load_timing.connect_timing.connect_end =
1952 now - base::TimeDelta::FromDays(1);
1953
[email protected]2ca01e52013-10-31 22:05:191954 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501955 RunURLRequestInterceptorLoadTimingTest(
1956 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591957
1958 // Proxy times, connect times, and DNS times should all be replaced with
1959 // request_start.
1960 EXPECT_EQ(load_timing_result.request_start,
1961 load_timing_result.proxy_resolve_start);
1962 EXPECT_EQ(load_timing_result.request_start,
1963 load_timing_result.proxy_resolve_end);
1964 EXPECT_EQ(load_timing_result.request_start,
1965 load_timing_result.connect_timing.dns_start);
1966 EXPECT_EQ(load_timing_result.request_start,
1967 load_timing_result.connect_timing.dns_end);
1968 EXPECT_EQ(load_timing_result.request_start,
1969 load_timing_result.connect_timing.connect_start);
1970 EXPECT_EQ(load_timing_result.request_start,
1971 load_timing_result.connect_timing.connect_end);
1972
1973 // Other times should have been left null.
1974 TestLoadTimingNotReusedWithProxy(load_timing_result,
1975 CONNECT_TIMING_HAS_DNS_TIMES);
1976}
1977
1978// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:501979TEST_F(URLRequestInterceptorTest,
1980 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:591981 base::TimeTicks now = base::TimeTicks::Now();
1982 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1983 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1984 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1985
[email protected]2ca01e52013-10-31 22:05:191986 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501987 RunURLRequestInterceptorLoadTimingTest(
1988 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591989
1990 // Proxy times and connect times should all be replaced with request_start.
1991 EXPECT_EQ(load_timing_result.request_start,
1992 load_timing_result.proxy_resolve_start);
1993 EXPECT_EQ(load_timing_result.request_start,
1994 load_timing_result.proxy_resolve_end);
1995
1996 // Other times should have been left null.
1997 TestLoadTimingReusedWithProxy(load_timing_result);
1998}
1999
2000// Make sure that URLRequest correctly adjusts connect times when they're before
2001// |request_start|, due to reusing a connected socket. The connected socket is
2002// not considered reused in this test (May be a preconnect).
2003//
2004// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502005TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592006 base::TimeTicks now = base::TimeTicks::Now();
2007 LoadTimingInfo job_load_timing =
2008 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2009 job_load_timing.connect_timing.connect_start =
2010 now - base::TimeDelta::FromDays(1);
2011 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2012 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2013 job_load_timing.connect_timing.connect_end =
2014 now - base::TimeDelta::FromDays(4);
2015
[email protected]2ca01e52013-10-31 22:05:192016 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502017 RunURLRequestInterceptorLoadTimingTest(
2018 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592019
2020 // Connect times, and SSL times should be replaced with request_start.
2021 EXPECT_EQ(load_timing_result.request_start,
2022 load_timing_result.connect_timing.connect_start);
2023 EXPECT_EQ(load_timing_result.request_start,
2024 load_timing_result.connect_timing.ssl_start);
2025 EXPECT_EQ(load_timing_result.request_start,
2026 load_timing_result.connect_timing.ssl_end);
2027 EXPECT_EQ(load_timing_result.request_start,
2028 load_timing_result.connect_timing.connect_end);
2029
2030 // Other times should have been left null.
2031 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2032}
2033
2034// Make sure that URLRequest correctly adjusts connect times when they're before
2035// |request_start|, due to reusing a connected socket in the case that there
2036// are also proxy times. The connected socket is not considered reused in this
2037// test (May be a preconnect).
2038//
2039// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502040TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592041 base::TimeTicks now = base::TimeTicks::Now();
2042 LoadTimingInfo job_load_timing =
2043 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2044 job_load_timing.connect_timing.connect_start =
2045 now - base::TimeDelta::FromDays(1);
2046 job_load_timing.connect_timing.connect_end =
2047 now - base::TimeDelta::FromDays(2);
2048
[email protected]2ca01e52013-10-31 22:05:192049 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502050 RunURLRequestInterceptorLoadTimingTest(
2051 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592052
2053 // Connect times should be replaced with proxy_resolve_end.
2054 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2055 load_timing_result.connect_timing.connect_start);
2056 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2057 load_timing_result.connect_timing.connect_end);
2058
2059 // Other times should have been left null.
2060 TestLoadTimingNotReusedWithProxy(load_timing_result,
2061 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2062}
2063
[email protected]316c1e5e2012-09-12 15:17:442064// Check that two different URL requests have different identifiers.
2065TEST_F(URLRequestTest, Identifiers) {
2066 TestDelegate d;
2067 TestURLRequestContext context;
davidben151423e2015-03-23 18:48:362068 scoped_ptr<URLRequest> req(
2069 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2070 scoped_ptr<URLRequest> other_req(
2071 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442072
mmenke19378d22014-09-09 04:12:592073 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442074}
2075
2076// Check that a failure to connect to the proxy is reported to the network
2077// delegate.
2078TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2079 MockHostResolver host_resolver;
2080 host_resolver.rules()->AddSimulatedFailure("*");
2081
[email protected]ceefd7fd2012-11-29 00:36:242082 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442083 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2084
2085 TestDelegate d;
davidben151423e2015-03-23 18:48:362086 scoped_ptr<URLRequest> req(
2087 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192088 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442089
[email protected]f7022f32014-08-21 16:32:192090 req->Start();
[email protected]255620da2013-08-19 13:14:292091 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442092
2093 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192094 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152095 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192096 EXPECT_TRUE(req->proxy_server().IsEmpty());
2097 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2098 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442099
2100 EXPECT_EQ(1, network_delegate.error_count());
2101 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2102 EXPECT_EQ(1, network_delegate.completed_requests());
2103}
2104
[email protected]cba24642014-08-15 20:49:592105// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442106// content is empty.
2107TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2108 TestDelegate d;
davidben151423e2015-03-23 18:48:362109 scoped_ptr<URLRequest> req(
2110 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192111 req->Start();
[email protected]255620da2013-08-19 13:14:292112 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442113 EXPECT_EQ("", d.data_received());
2114 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2115}
2116
[email protected]5033ab82013-03-22 20:17:462117// Make sure that SetPriority actually sets the URLRequest's priority
2118// correctly, both before and after start.
2119TEST_F(URLRequestTest, SetPriorityBasic) {
2120 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192121 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362122 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192123 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462124
[email protected]f7022f32014-08-21 16:32:192125 req->SetPriority(LOW);
2126 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462127
[email protected]f7022f32014-08-21 16:32:192128 req->Start();
2129 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462130
[email protected]f7022f32014-08-21 16:32:192131 req->SetPriority(MEDIUM);
2132 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462133}
2134
2135// Make sure that URLRequest calls SetPriority on a job before calling
2136// Start on it.
2137TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2138 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192139 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362140 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192141 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462142
2143 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192144 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502145 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462146 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2147
[email protected]f7022f32014-08-21 16:32:192148 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462149
[email protected]f7022f32014-08-21 16:32:192150 req->Start();
[email protected]5033ab82013-03-22 20:17:462151 EXPECT_EQ(LOW, job->priority());
2152}
2153
2154// Make sure that URLRequest passes on its priority updates to its
2155// job.
2156TEST_F(URLRequestTest, SetJobPriority) {
2157 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192158 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362159 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462160
2161 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192162 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502163 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462164
[email protected]f7022f32014-08-21 16:32:192165 req->SetPriority(LOW);
2166 req->Start();
[email protected]5033ab82013-03-22 20:17:462167 EXPECT_EQ(LOW, job->priority());
2168
[email protected]f7022f32014-08-21 16:32:192169 req->SetPriority(MEDIUM);
2170 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462171 EXPECT_EQ(MEDIUM, job->priority());
2172}
2173
[email protected]bb1c4662013-11-14 00:00:072174// Setting the IGNORE_LIMITS load flag should be okay if the priority
2175// is MAXIMUM_PRIORITY.
2176TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2177 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192178 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362179 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192180 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072181
2182 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192183 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]bb1c4662013-11-14 00:00:072184 AddTestInterceptor()->set_main_intercept_job(job.get());
2185
[email protected]f7022f32014-08-21 16:32:192186 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2187 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072188
[email protected]f7022f32014-08-21 16:32:192189 req->SetPriority(MAXIMUM_PRIORITY);
2190 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072191
[email protected]f7022f32014-08-21 16:32:192192 req->Start();
2193 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072194 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2195}
2196
nick5d570de92015-05-04 20:16:162197namespace {
2198
2199// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552200class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442201 public:
tommycli59a63432015-11-06 00:10:552202 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2203 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272204 }
tommycli59a63432015-11-06 00:10:552205
2206 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2207};
tommyclieae5f75f2015-11-05 19:07:272208
nick5d570de92015-05-04 20:16:162209} // namespace
2210
[email protected]f2f31b32013-01-16 23:24:092211TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442212 LocalHttpTestServer test_server;
2213 ASSERT_TRUE(test_server.Start());
2214
2215 TestURLRequestContext context;
2216 scoped_refptr<DelayedCookieMonster> delayed_cm =
2217 new DelayedCookieMonster();
2218 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502219 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442220
2221 // Set up a cookie.
2222 {
2223 TestNetworkDelegate network_delegate;
2224 context.set_network_delegate(&network_delegate);
2225 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192226 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552227 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362228 &d));
[email protected]f7022f32014-08-21 16:32:192229 req->Start();
[email protected]255620da2013-08-19 13:14:292230 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442231 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2232 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2233 EXPECT_EQ(1, network_delegate.set_cookie_count());
2234 }
2235
2236 // Verify that the cookie is set.
2237 {
2238 TestNetworkDelegate network_delegate;
2239 context.set_network_delegate(&network_delegate);
2240 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192241 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552242 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192243 req->Start();
[email protected]255620da2013-08-19 13:14:292244 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442245
2246 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2247 != std::string::npos);
2248 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2249 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2250 }
2251}
2252
[email protected]f2f31b32013-01-16 23:24:092253TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442254 LocalHttpTestServer test_server;
2255 ASSERT_TRUE(test_server.Start());
2256
2257 // Set up a cookie.
2258 {
2259 TestNetworkDelegate network_delegate;
2260 default_context_.set_network_delegate(&network_delegate);
2261 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192262 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552263 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362264 &d));
[email protected]f7022f32014-08-21 16:32:192265 req->Start();
[email protected]255620da2013-08-19 13:14:292266 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442267 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2268 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2269 }
2270
2271 // Verify that the cookie is set.
2272 {
2273 TestNetworkDelegate network_delegate;
2274 default_context_.set_network_delegate(&network_delegate);
2275 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192276 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552277 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192278 req->Start();
[email protected]255620da2013-08-19 13:14:292279 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442280
2281 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2282 != std::string::npos);
2283 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2284 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2285 }
2286
2287 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2288 {
2289 TestNetworkDelegate network_delegate;
2290 default_context_.set_network_delegate(&network_delegate);
2291 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192292 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552293 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192294 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2295 req->Start();
[email protected]255620da2013-08-19 13:14:292296 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442297
2298 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2299 == std::string::npos);
2300
2301 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2302 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2303 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2304 }
2305}
2306
2307TEST_F(URLRequestTest, DoNotSaveCookies) {
2308 LocalHttpTestServer test_server;
2309 ASSERT_TRUE(test_server.Start());
2310
2311 // Set up a cookie.
2312 {
2313 TestNetworkDelegate network_delegate;
2314 default_context_.set_network_delegate(&network_delegate);
2315 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192316 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552317 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362318 &d));
[email protected]f7022f32014-08-21 16:32:192319 req->Start();
[email protected]255620da2013-08-19 13:14:292320 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442321
2322 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2323 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2324 EXPECT_EQ(1, network_delegate.set_cookie_count());
2325 }
2326
2327 // Try to set-up another cookie and update the previous cookie.
2328 {
2329 TestNetworkDelegate network_delegate;
2330 default_context_.set_network_delegate(&network_delegate);
2331 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192332 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552333 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362334 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192335 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2336 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442337
[email protected]255620da2013-08-19 13:14:292338 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442339
2340 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2341 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2342 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2343 EXPECT_EQ(0, network_delegate.set_cookie_count());
2344 }
2345
2346 // Verify the cookies weren't saved or updated.
2347 {
2348 TestNetworkDelegate network_delegate;
2349 default_context_.set_network_delegate(&network_delegate);
2350 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192351 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552352 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192353 req->Start();
[email protected]255620da2013-08-19 13:14:292354 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442355
2356 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2357 == std::string::npos);
2358 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2359 != std::string::npos);
2360
2361 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2362 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2363 EXPECT_EQ(0, network_delegate.set_cookie_count());
2364 }
2365}
2366
2367TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2368 LocalHttpTestServer test_server;
2369 ASSERT_TRUE(test_server.Start());
2370
2371 // Set up a cookie.
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("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362378 &d));
[email protected]f7022f32014-08-21 16:32:192379 req->Start();
[email protected]255620da2013-08-19 13:14:292380 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442381
2382 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2383 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2384 }
2385
2386 // Verify that the cookie is set.
2387 {
2388 TestNetworkDelegate network_delegate;
2389 default_context_.set_network_delegate(&network_delegate);
2390 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192391 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552392 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192393 req->Start();
[email protected]255620da2013-08-19 13:14:292394 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442395
2396 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2397 != std::string::npos);
2398
2399 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2400 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2401 }
2402
2403 // Verify that the cookie isn't sent.
2404 {
2405 TestNetworkDelegate network_delegate;
2406 default_context_.set_network_delegate(&network_delegate);
2407 TestDelegate d;
2408 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192409 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552410 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192411 req->Start();
[email protected]255620da2013-08-19 13:14:292412 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442413
2414 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2415 == std::string::npos);
2416
[email protected]22e045f2013-09-20 03:54:032417 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442418 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2419 }
2420}
2421
2422TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2423 LocalHttpTestServer test_server;
2424 ASSERT_TRUE(test_server.Start());
2425
2426 // Set up a cookie.
2427 {
2428 TestNetworkDelegate network_delegate;
2429 default_context_.set_network_delegate(&network_delegate);
2430 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192431 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552432 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362433 &d));
[email protected]f7022f32014-08-21 16:32:192434 req->Start();
[email protected]255620da2013-08-19 13:14:292435 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442436
2437 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2438 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2439 }
2440
2441 // Try to set-up another cookie and update the previous cookie.
2442 {
2443 TestNetworkDelegate network_delegate;
2444 default_context_.set_network_delegate(&network_delegate);
2445 TestDelegate d;
2446 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192447 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552448 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362449 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192450 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442451
[email protected]255620da2013-08-19 13:14:292452 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442453
2454 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2455 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2456 }
2457
2458 // Verify the cookies weren't saved or updated.
2459 {
2460 TestNetworkDelegate network_delegate;
2461 default_context_.set_network_delegate(&network_delegate);
2462 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192463 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552464 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &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_TRUE(d.data_received().find("CookieToNotSave=1")
2469 == std::string::npos);
2470 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2471 != std::string::npos);
2472
2473 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2474 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2475 }
2476}
2477
2478TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2479 LocalHttpTestServer test_server;
2480 ASSERT_TRUE(test_server.Start());
2481
2482 // Set up an empty cookie.
2483 {
2484 TestNetworkDelegate network_delegate;
2485 default_context_.set_network_delegate(&network_delegate);
2486 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192487 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552488 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192489 req->Start();
[email protected]255620da2013-08-19 13:14:292490 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442491
2492 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2493 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2494 EXPECT_EQ(0, network_delegate.set_cookie_count());
2495 }
2496}
2497
2498TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2499 LocalHttpTestServer test_server;
2500 ASSERT_TRUE(test_server.Start());
2501
2502 // Set up a cookie.
2503 {
2504 TestNetworkDelegate network_delegate;
2505 default_context_.set_network_delegate(&network_delegate);
2506 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192507 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552508 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362509 &d));
[email protected]f7022f32014-08-21 16:32:192510 req->Start();
[email protected]255620da2013-08-19 13:14:292511 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442512
2513 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2514 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2515 }
2516
2517 // Verify that the cookie is set.
2518 {
2519 TestNetworkDelegate network_delegate;
2520 default_context_.set_network_delegate(&network_delegate);
2521 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192522 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552523 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192524 req->Start();
[email protected]255620da2013-08-19 13:14:292525 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442526
2527 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2528 != std::string::npos);
2529
2530 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2531 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2532 }
2533
2534 // Verify that the cookie isn't sent.
2535 {
2536 TestNetworkDelegate network_delegate;
2537 default_context_.set_network_delegate(&network_delegate);
2538 TestDelegate d;
2539 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192540 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552541 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192542 req->Start();
[email protected]255620da2013-08-19 13:14:292543 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442544
2545 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2546 == std::string::npos);
2547
[email protected]22e045f2013-09-20 03:54:032548 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442549 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2550 }
2551}
2552
2553TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2554 LocalHttpTestServer test_server;
2555 ASSERT_TRUE(test_server.Start());
2556
2557 // Set up a cookie.
2558 {
2559 TestNetworkDelegate network_delegate;
2560 default_context_.set_network_delegate(&network_delegate);
2561 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192562 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552563 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362564 &d));
[email protected]f7022f32014-08-21 16:32:192565 req->Start();
[email protected]255620da2013-08-19 13:14:292566 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442567
2568 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2569 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2570 }
2571
2572 // Try to set-up another cookie and update the previous cookie.
2573 {
2574 TestNetworkDelegate network_delegate;
2575 default_context_.set_network_delegate(&network_delegate);
2576 TestDelegate d;
2577 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192578 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552579 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362580 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192581 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442582
[email protected]255620da2013-08-19 13:14:292583 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442584
2585 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2586 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2587 }
2588
2589 // Verify the cookies weren't saved or updated.
2590 {
2591 TestNetworkDelegate network_delegate;
2592 default_context_.set_network_delegate(&network_delegate);
2593 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192594 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552595 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &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_TRUE(d.data_received().find("CookieToNotSave=1")
2600 == std::string::npos);
2601 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2602 != std::string::npos);
2603
2604 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2605 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2606 }
2607}
2608
mkwst3f3daac2015-02-26 20:15:262609TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2610 LocalHttpTestServer test_server;
2611 ASSERT_TRUE(test_server.Start());
2612
2613 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2614 // LocalHttpTestServer points).
2615 {
2616 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412617 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262618 default_context_.set_network_delegate(&network_delegate);
2619
2620 TestDelegate d;
2621 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2622 test_server.GetURL(
tommycli59a63432015-11-06 00:10:552623 "/set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
davidben151423e2015-03-23 18:48:362624 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262625 req->Start();
2626 base::RunLoop().Run();
2627 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2628 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2629 EXPECT_EQ(1, network_delegate.set_cookie_count());
2630 }
2631
2632 // Verify that the cookie is sent for first-party requests.
2633 {
2634 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412635 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262636 default_context_.set_network_delegate(&network_delegate);
2637 TestDelegate d;
2638 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552639 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2640 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst3f3daac2015-02-26 20:15:262641 req->Start();
2642 base::RunLoop().Run();
2643
2644 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2645 std::string::npos);
2646 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2647 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2648 }
2649
2650 // Verify that the cookie is not-sent for non-first-party requests.
2651 {
2652 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412653 network_delegate.set_experimental_cookie_features_enabled(true);
mkwst3f3daac2015-02-26 20:15:262654 default_context_.set_network_delegate(&network_delegate);
2655 TestDelegate d;
2656 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552657 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262658 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2659 req->Start();
2660 base::RunLoop().Run();
2661
2662 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2663 std::string::npos);
2664 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2665 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2666 }
2667}
2668
mkwst0513c9d2015-04-01 05:53:152669TEST_F(URLRequestTest, FirstPartyOnlyCookiesDisabled) {
2670 LocalHttpTestServer test_server;
2671 ASSERT_TRUE(test_server.Start());
2672
2673 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2674 // LocalHttpTestServer points).
2675 {
2676 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412677 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152678 default_context_.set_network_delegate(&network_delegate);
2679
2680 TestDelegate d;
2681 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2682 test_server.GetURL(
tommycli59a63432015-11-06 00:10:552683 "/set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
mkwst0513c9d2015-04-01 05:53:152684 DEFAULT_PRIORITY, &d));
2685 req->Start();
2686 base::RunLoop().Run();
2687 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2688 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2689 EXPECT_EQ(1, network_delegate.set_cookie_count());
2690 }
2691
2692 // Verify that the cookie is sent for first-party requests.
2693 {
2694 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412695 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152696 default_context_.set_network_delegate(&network_delegate);
2697 TestDelegate d;
2698 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552699 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2700 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst0513c9d2015-04-01 05:53:152701 req->Start();
2702 base::RunLoop().Run();
2703
2704 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2705 std::string::npos);
2706 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2707 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2708 }
2709
2710 // Verify that the cookie is also sent for non-first-party requests.
2711 {
2712 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412713 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152714 default_context_.set_network_delegate(&network_delegate);
2715 TestDelegate d;
2716 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552717 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst0513c9d2015-04-01 05:53:152718 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2719 req->Start();
2720 base::RunLoop().Run();
2721
2722 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2723 std::string::npos);
2724 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2725 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2726 }
2727}
2728
estark557a5eb82015-12-01 22:57:102729// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:362730TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:552731 EmbeddedTestServer http_server;
2732 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362733 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552734 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2735 https_server.AddDefaultHandlers(
2736 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2737 ASSERT_TRUE(http_server.Start());
2738 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362739
2740 TestExperimentalFeaturesNetworkDelegate network_delegate;
2741 TestURLRequestContext context(true);
2742 context.set_network_delegate(&network_delegate);
2743 context.Init();
2744
estark557a5eb82015-12-01 22:57:102745 // Try to set a Secure __Secure- cookie, with experimental features
estarkcd39c11f2015-10-19 19:46:362746 // enabled.
2747 {
2748 TestDelegate d;
2749 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102750 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362751 DEFAULT_PRIORITY, &d));
2752 req->Start();
2753 base::RunLoop().Run();
2754 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2755 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2756 }
2757
2758 // Verify that the cookie is not set.
2759 {
2760 TestDelegate d;
2761 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552762 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362763 req->Start();
2764 base::RunLoop().Run();
2765
estark557a5eb82015-12-01 22:57:102766 EXPECT_TRUE(d.data_received().find("__Secure-nonsecure-origin=1") ==
estarkcd39c11f2015-10-19 19:46:362767 std::string::npos);
2768 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2769 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2770 }
2771}
2772
2773TEST_F(URLRequestTest, SecureCookiePrefixNonexperimental) {
tommycli59a63432015-11-06 00:10:552774 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2775 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362776 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552777 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362778
2779 TestNetworkDelegate network_delegate;
2780 TestURLRequestContext context(true);
2781 context.set_network_delegate(&network_delegate);
2782 context.Init();
2783
2784 // Without experimental features, there should be no restrictions on
estark557a5eb82015-12-01 22:57:102785 // __Secure- cookies.
estarkcd39c11f2015-10-19 19:46:362786
estark557a5eb82015-12-01 22:57:102787 // Set a non-Secure cookie with the __Secure- prefix.
estarkcd39c11f2015-10-19 19:46:362788 {
2789 TestDelegate d;
2790 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102791 https_server.GetURL(
2792 "/set-cookie?__Secure-nonsecure-not-experimental=1"),
estarkcd39c11f2015-10-19 19:46:362793 DEFAULT_PRIORITY, &d));
2794 req->Start();
2795 base::RunLoop().Run();
2796 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2797 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2798 }
2799
estark557a5eb82015-12-01 22:57:102800 // Set a Secure cookie with the __Secure- prefix.
estarkcd39c11f2015-10-19 19:46:362801 {
2802 TestDelegate d;
2803 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552804 https_server.GetURL(
estark557a5eb82015-12-01 22:57:102805 "/set-cookie?__Secure-secure-not-experimental=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362806 DEFAULT_PRIORITY, &d));
2807 req->Start();
2808 base::RunLoop().Run();
2809 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2810 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2811 }
2812
2813 // Verify that the cookies are set. Neither should have any
2814 // restrictions because the experimental flag is off.
2815 {
2816 TestDelegate d;
2817 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552818 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362819 req->Start();
2820 base::RunLoop().Run();
2821
estark557a5eb82015-12-01 22:57:102822 EXPECT_TRUE(d.data_received().find("__Secure-secure-not-experimental=1") !=
estarkcd39c11f2015-10-19 19:46:362823 std::string::npos);
2824 EXPECT_TRUE(
estark557a5eb82015-12-01 22:57:102825 d.data_received().find("__Secure-nonsecure-not-experimental=1") !=
estarkcd39c11f2015-10-19 19:46:362826 std::string::npos);
2827 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2828 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2829 }
2830}
2831
2832TEST_F(URLRequestTest, SecureCookiePrefixExperimentalNonsecure) {
tommycli59a63432015-11-06 00:10:552833 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2834 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362835 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552836 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362837
2838 TestExperimentalFeaturesNetworkDelegate network_delegate;
2839 TestURLRequestContext context(true);
2840 context.set_network_delegate(&network_delegate);
2841 context.Init();
2842
estark557a5eb82015-12-01 22:57:102843 // Try to set a non-Secure __Secure- cookie, with experimental features
estarkcd39c11f2015-10-19 19:46:362844 // enabled.
2845 {
2846 TestDelegate d;
tommycli59a63432015-11-06 00:10:552847 scoped_ptr<URLRequest> req(
estark557a5eb82015-12-01 22:57:102848 context.CreateRequest(https_server.GetURL("/set-cookie?__Secure-foo=1"),
tommycli59a63432015-11-06 00:10:552849 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362850 req->Start();
2851 base::RunLoop().Run();
2852 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2853 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2854 }
2855
2856 // Verify that the cookie is not set.
2857 {
2858 TestDelegate d;
2859 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552860 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362861 req->Start();
2862 base::RunLoop().Run();
2863
estark557a5eb82015-12-01 22:57:102864 EXPECT_TRUE(d.data_received().find("__Secure-foo=1") == std::string::npos);
estarkcd39c11f2015-10-19 19:46:362865 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2866 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2867 }
2868}
2869
2870TEST_F(URLRequestTest, SecureCookiePrefixExperimentalSecure) {
tommycli59a63432015-11-06 00:10:552871 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2872 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362873 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552874 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362875
2876 TestExperimentalFeaturesNetworkDelegate network_delegate;
2877 TestURLRequestContext context(true);
2878 context.set_network_delegate(&network_delegate);
2879 context.Init();
2880
estark557a5eb82015-12-01 22:57:102881 // Try to set a Secure __Secure- cookie, with experimental features
estarkcd39c11f2015-10-19 19:46:362882 // enabled.
2883 {
2884 TestDelegate d;
2885 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102886 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
tommycli59a63432015-11-06 00:10:552887 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362888 req->Start();
2889 base::RunLoop().Run();
2890 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2891 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2892 }
2893
2894 // Verify that the cookie is set.
2895 {
2896 TestDelegate d;
2897 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552898 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362899 req->Start();
2900 base::RunLoop().Run();
2901
estark557a5eb82015-12-01 22:57:102902 EXPECT_TRUE(d.data_received().find("__Secure-bar=1") != std::string::npos);
estarkcd39c11f2015-10-19 19:46:362903 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2904 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2905 }
2906}
2907
mmenkefb18c772015-09-30 22:22:502908// Tests that a request is cancelled while entering suspend mode. Uses mocks
2909// rather than a spawned test server because the connection used to talk to
2910// the test server is affected by entering suspend mode on Android.
2911TEST_F(URLRequestTest, CancelOnSuspend) {
2912 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
2913 base::PowerMonitor power_monitor(make_scoped_ptr(power_monitor_source));
2914
2915 URLRequestFailedJob::AddUrlHandler();
2916
2917 TestDelegate d;
2918 // Request that just hangs.
2919 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
2920 scoped_ptr<URLRequest> r(
2921 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
2922 r->Start();
2923
2924 power_monitor_source->Suspend();
2925 // Wait for the suspend notification to cause the request to fail.
2926 base::RunLoop().Run();
2927 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
2928 EXPECT_TRUE(d.request_failed());
2929 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2930
2931 URLRequestFilter::GetInstance()->ClearHandlers();
2932
2933 // Shouldn't be needed, but just in case.
2934 power_monitor_source->Resume();
2935}
2936
[email protected]5095cd72012-11-01 10:29:162937// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2938// value for the |fixed_date| argument given to the constructor.
2939class FixedDateNetworkDelegate : public TestNetworkDelegate {
2940 public:
2941 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2942 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:202943 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:162944
[email protected]cba24642014-08-15 20:49:592945 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:202946 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592947 URLRequest* request,
2948 const CompletionCallback& callback,
2949 const HttpResponseHeaders* original_response_headers,
2950 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:132951 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:162952
2953 private:
2954 std::string fixed_date_;
2955
2956 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2957};
2958
2959int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592960 URLRequest* request,
2961 const CompletionCallback& callback,
2962 const HttpResponseHeaders* original_response_headers,
2963 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:162964 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:592965 HttpResponseHeaders* new_response_headers =
2966 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:162967
2968 new_response_headers->RemoveHeader("Date");
2969 new_response_headers->AddHeader("Date: " + fixed_date_);
2970
2971 *override_response_headers = new_response_headers;
2972 return TestNetworkDelegate::OnHeadersReceived(request,
2973 callback,
2974 original_response_headers,
[email protected]5f714132014-03-26 10:41:162975 override_response_headers,
2976 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:162977}
2978
2979// Test that cookie expiration times are adjusted for server/client clock
2980// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2981// headers by defaulting to GMT. (crbug.com/135131)
2982TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2983 LocalHttpTestServer test_server;
2984 ASSERT_TRUE(test_server.Start());
2985
2986 // Set up an expired cookie.
2987 {
2988 TestNetworkDelegate network_delegate;
2989 default_context_.set_network_delegate(&network_delegate);
2990 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192991 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192992 test_server.GetURL(
tommycli59a63432015-11-06 00:10:552993 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362994 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192995 req->Start();
[email protected]255620da2013-08-19 13:14:292996 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162997 }
2998 // Verify that the cookie is not set.
2999 {
3000 TestNetworkDelegate network_delegate;
3001 default_context_.set_network_delegate(&network_delegate);
3002 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193003 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553004 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193005 req->Start();
[email protected]255620da2013-08-19 13:14:293006 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163007
3008 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3009 }
3010 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3011 {
3012 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3013 default_context_.set_network_delegate(&network_delegate);
3014 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193015 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193016 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553017 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363018 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193019 req->Start();
[email protected]255620da2013-08-19 13:14:293020 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163021 }
3022 // Verify that the cookie is set.
3023 {
3024 TestNetworkDelegate network_delegate;
3025 default_context_.set_network_delegate(&network_delegate);
3026 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193027 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553028 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193029 req->Start();
[email protected]255620da2013-08-19 13:14:293030 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163031
3032 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3033 }
3034}
3035
3036
[email protected]316c1e5e2012-09-12 15:17:443037// Check that it is impossible to change the referrer in the extra headers of
3038// an URLRequest.
3039TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3040 LocalHttpTestServer test_server;
3041 ASSERT_TRUE(test_server.Start());
3042
3043 // If extra headers contain referer and the request contains a referer,
3044 // only the latter shall be respected.
3045 {
3046 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193047 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553048 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193049 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443050
3051 HttpRequestHeaders headers;
3052 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193053 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443054
[email protected]f7022f32014-08-21 16:32:193055 req->Start();
[email protected]255620da2013-08-19 13:14:293056 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443057
3058 EXPECT_EQ("http://foo.com/", d.data_received());
3059 }
3060
3061 // If extra headers contain a referer but the request does not, no referer
3062 // shall be sent in the header.
3063 {
3064 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193065 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553066 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443067
3068 HttpRequestHeaders headers;
3069 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193070 req->SetExtraRequestHeaders(headers);
3071 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443072
[email protected]f7022f32014-08-21 16:32:193073 req->Start();
[email protected]255620da2013-08-19 13:14:293074 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443075
3076 EXPECT_EQ("None", d.data_received());
3077 }
3078}
3079
[email protected]b89290212009-08-14 22:37:353080class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113081 public:
mmenke9f2ec60c2015-06-01 20:59:473082 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113083
[email protected]b89290212009-08-14 22:37:353084 protected:
[email protected]21184962011-10-26 00:50:303085 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3086 // |request_method| is the method to use for the initial request.
3087 // |redirect_method| is the method that is expected to be used for the second
3088 // request, after redirection.
3089 // If |include_data| is true, data is uploaded with the request. The
3090 // response body is expected to match it exactly, if and only if
3091 // |request_method| == |redirect_method|.
3092 void HTTPRedirectMethodTest(const GURL& redirect_url,
3093 const std::string& request_method,
3094 const std::string& redirect_method,
3095 bool include_data) {
3096 static const char kData[] = "hello world";
3097 TestDelegate d;
davidben151423e2015-03-23 18:48:363098 scoped_ptr<URLRequest> req(
3099 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193100 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303101 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073102 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303103 HttpRequestHeaders headers;
3104 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513105 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543106 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193107 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303108 }
[email protected]f7022f32014-08-21 16:32:193109 req->Start();
[email protected]255620da2013-08-19 13:14:293110 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193111 EXPECT_EQ(redirect_method, req->method());
3112 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
3113 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:303114 if (include_data) {
3115 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543116 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3117 HttpRequestHeaders::kContentLength));
3118 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3119 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303120 EXPECT_EQ(kData, d.data_received());
3121 } else {
svaldez5b3a8972015-10-09 23:23:543122 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3123 HttpRequestHeaders::kContentLength));
3124 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3125 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303126 EXPECT_NE(kData, d.data_received());
3127 }
3128 }
3129 if (HasFailure())
3130 LOG(WARNING) << "Request method was: " << request_method;
3131 }
3132
jww5fe460ff2015-03-28 00:22:513133 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3134 // |request_method| is the method to use for the initial request.
3135 // |redirect_method| is the method that is expected to be used for the second
3136 // request, after redirection.
3137 // |origin_value| is the expected value for the Origin header after
3138 // redirection. If empty, expects that there will be no Origin header.
3139 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3140 const std::string& request_method,
3141 const std::string& redirect_method,
3142 const std::string& origin_value) {
3143 TestDelegate d;
3144 scoped_ptr<URLRequest> req(
3145 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3146 req->set_method(request_method);
3147 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3148 redirect_url.GetOrigin().spec(), false);
3149 req->Start();
3150
3151 base::RunLoop().Run();
3152
3153 EXPECT_EQ(redirect_method, req->method());
3154 // Note that there is no check for request success here because, for
3155 // purposes of testing, the request very well may fail. For example, if the
3156 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3157 // origin, there is not an HTTPS server in this unit test framework, so the
3158 // request would fail. However, that's fine, as long as the request headers
3159 // are in order and pass the checks below.
3160 if (origin_value.empty()) {
3161 EXPECT_FALSE(
3162 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3163 } else {
3164 std::string origin_header;
3165 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3166 HttpRequestHeaders::kOrigin, &origin_header));
3167 EXPECT_EQ(origin_value, origin_header);
3168 }
3169 }
3170
[email protected]762d2db2010-01-11 19:03:013171 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013172 const int kMsgSize = 20000; // multiple of 10
3173 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483174 char* uploadBytes = new char[kMsgSize+1];
3175 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013176 char marker = 'a';
3177 for (int idx = 0; idx < kMsgSize/10; idx++) {
3178 memcpy(ptr, "----------", 10);
3179 ptr += 10;
3180 if (idx % 100 == 0) {
3181 ptr--;
3182 *ptr++ = marker;
3183 if (++marker > 'z')
3184 marker = 'a';
3185 }
3186 }
3187 uploadBytes[kMsgSize] = '\0';
3188
[email protected]762d2db2010-01-11 19:03:013189 for (int i = 0; i < kIterations; ++i) {
3190 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193191 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553192 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193193 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013194
mmenkecbc2b712014-10-09 20:29:073195 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013196
[email protected]f7022f32014-08-21 16:32:193197 r->Start();
3198 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013199
[email protected]255620da2013-08-19 13:14:293200 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013201
[email protected]329b68b2012-11-14 17:54:273202 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:193203 << "request failed: " << r->status().status()
3204 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:013205
3206 EXPECT_FALSE(d.received_data_before_response());
3207 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013208 }
3209 delete[] uploadBytes;
3210 }
3211
[email protected]ef2bf422012-05-11 03:27:093212 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:223213 r->AppendChunkToUpload("a", 1, false);
3214 r->AppendChunkToUpload("bcd", 3, false);
3215 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
3216 r->AppendChunkToUpload("\r\n\r\n", 4, false);
3217 r->AppendChunkToUpload("0", 1, false);
3218 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:113219 }
3220
[email protected]ef2bf422012-05-11 03:27:093221 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:113222 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:273223 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:113224 "abcdthis is a longer chunk than before.\r\n\r\n02323";
3225
[email protected]329b68b2012-11-14 17:54:273226 ASSERT_EQ(1, d->response_started_count())
3227 << "request failed: " << r->status().status()
3228 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:113229
3230 EXPECT_FALSE(d->received_data_before_response());
3231
[email protected]329b68b2012-11-14 17:54:273232 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
3233 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:113234 }
3235
[email protected]ede03212012-09-07 12:52:263236 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343237 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193238 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553239 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363240 base::IntToString(num_cookies)),
3241 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343242
[email protected]f7022f32014-08-21 16:32:193243 r->Start();
3244 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343245
[email protected]255620da2013-08-19 13:14:293246 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343247
[email protected]f7022f32014-08-21 16:32:193248 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:343249
tommycli59a63432015-11-06 00:10:553250 if (!is_success)
[email protected]f7022f32014-08-21 16:32:193251 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:343252
3253 return is_success;
3254 }
3255
tommycli59a63432015-11-06 00:10:553256 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503257
tommycli59a63432015-11-06 00:10:553258 private:
[email protected]1700c6a2012-02-22 18:07:073259 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353260};
3261
tommycli59a63432015-11-06 00:10:553262namespace {
3263
3264scoped_ptr<test_server::HttpResponse> HandleRedirectConnect(
3265 const test_server::HttpRequest& request) {
3266 if (request.headers.find("Host") == request.headers.end() ||
3267 request.headers.at("Host") != "www.redirect.com" ||
3268 request.method != test_server::METHOD_CONNECT) {
3269 return nullptr;
3270 }
3271
3272 scoped_ptr<test_server::BasicHttpResponse> http_response(
3273 new test_server::BasicHttpResponse);
3274 http_response->set_code(HTTP_FOUND);
3275 http_response->AddCustomHeader("Location",
3276 "http://www.destination.com/foo.js");
3277 return http_response.Pass();
3278}
3279
3280} // namespace
3281
3282// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113283// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553284// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113285// follow.
[email protected]f2f31b32013-01-16 23:24:093286TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553287 http_test_server()->RegisterRequestHandler(
3288 base::Bind(&HandleRedirectConnect));
3289 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113290
[email protected]ceefd7fd2012-11-29 00:36:243291 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043292 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553293 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503294
[email protected]d1ec59082009-02-11 02:48:153295 TestDelegate d;
3296 {
[email protected]f7022f32014-08-21 16:32:193297 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363298 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193299 r->Start();
3300 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153301
[email protected]255620da2013-08-19 13:14:293302 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153303
[email protected]f7022f32014-08-21 16:32:193304 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153305 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193306 EXPECT_TRUE(r->proxy_server().IsEmpty());
3307 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083308 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153309 // We should not have followed the redirect.
3310 EXPECT_EQ(0, d.received_redirect_count());
3311 }
3312}
3313
[email protected]8202d0c2011-02-23 08:31:143314// This is the same as the previous test, but checks that the network delegate
3315// registers the error.
[email protected]c044616e2013-02-20 02:01:263316TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553317 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143318
[email protected]ceefd7fd2012-11-29 00:36:243319 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043320 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553321 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503322
[email protected]8202d0c2011-02-23 08:31:143323 TestDelegate d;
3324 {
[email protected]f7022f32014-08-21 16:32:193325 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363326 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193327 r->Start();
3328 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143329
[email protected]255620da2013-08-19 13:14:293330 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143331
[email protected]f7022f32014-08-21 16:32:193332 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153333 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193334 EXPECT_TRUE(r->proxy_server().IsEmpty());
3335 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143336 EXPECT_EQ(1, d.response_started_count());
3337 // We should not have followed the redirect.
3338 EXPECT_EQ(0, d.received_redirect_count());
3339
3340 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053341 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143342 }
3343}
3344
[email protected]dc5a5cf2012-09-26 02:49:303345// Tests that we can block and asynchronously return OK in various stages.
3346TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3347 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3348 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3349 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3350 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3351 };
3352 static const size_t blocking_stages_length = arraysize(blocking_stages);
3353
tommycli59a63432015-11-06 00:10:553354 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:303355
3356 TestDelegate d;
3357 BlockingNetworkDelegate network_delegate(
3358 BlockingNetworkDelegate::USER_CALLBACK);
3359 network_delegate.set_block_on(
3360 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3361 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3362 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3363
3364 TestURLRequestContext context(true);
3365 context.set_network_delegate(&network_delegate);
3366 context.Init();
3367
3368 {
[email protected]f7022f32014-08-21 16:32:193369 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553370 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303371
[email protected]f7022f32014-08-21 16:32:193372 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303373 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293374 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303375 EXPECT_EQ(blocking_stages[i],
3376 network_delegate.stage_blocked_for_callback());
3377 network_delegate.DoCallback(OK);
3378 }
[email protected]255620da2013-08-19 13:14:293379 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193380 EXPECT_EQ(200, r->GetResponseCode());
3381 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303382 EXPECT_EQ(1, network_delegate.created_requests());
3383 EXPECT_EQ(0, network_delegate.destroyed_requests());
3384 }
3385 EXPECT_EQ(1, network_delegate.destroyed_requests());
3386}
3387
[email protected]4c76d7c2011-04-15 19:14:123388// Tests that the network delegate can block and cancel a request.
3389TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:553390 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123391
3392 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303393 BlockingNetworkDelegate network_delegate(
3394 BlockingNetworkDelegate::AUTO_CALLBACK);
3395 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3396 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123397
[email protected]d5a4dd62012-05-23 01:41:043398 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553399 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503400
[email protected]4c76d7c2011-04-15 19:14:123401 {
[email protected]f7022f32014-08-21 16:32:193402 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553403 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123404
[email protected]f7022f32014-08-21 16:32:193405 r->Start();
[email protected]255620da2013-08-19 13:14:293406 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123407
[email protected]f7022f32014-08-21 16:32:193408 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153409 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193410 EXPECT_TRUE(r->proxy_server().IsEmpty());
3411 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123412 EXPECT_EQ(1, network_delegate.created_requests());
3413 EXPECT_EQ(0, network_delegate.destroyed_requests());
3414 }
3415 EXPECT_EQ(1, network_delegate.destroyed_requests());
3416}
3417
[email protected]b4438d32012-09-27 06:15:303418// Helper function for NetworkDelegateCancelRequestAsynchronously and
3419// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3420// delegate operating in |block_mode| and a request for |url|. It blocks the
3421// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3422void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3423 BlockingNetworkDelegate::Stage stage,
3424 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363425 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303426 BlockingNetworkDelegate network_delegate(block_mode);
3427 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3428 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363429
[email protected]b4438d32012-09-27 06:15:303430 TestURLRequestContext context(true);
3431 context.set_network_delegate(&network_delegate);
3432 context.Init();
[email protected]3cd384c602011-08-31 16:12:363433
3434 {
davidben151423e2015-03-23 18:48:363435 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363436
[email protected]f7022f32014-08-21 16:32:193437 r->Start();
[email protected]255620da2013-08-19 13:14:293438 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363439
[email protected]f7022f32014-08-21 16:32:193440 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153441 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193442 EXPECT_TRUE(r->proxy_server().IsEmpty());
3443 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363444 EXPECT_EQ(1, network_delegate.created_requests());
3445 EXPECT_EQ(0, network_delegate.destroyed_requests());
3446 }
3447 EXPECT_EQ(1, network_delegate.destroyed_requests());
3448}
3449
[email protected]b4438d32012-09-27 06:15:303450// The following 3 tests check that the network delegate can cancel a request
3451// synchronously in various stages of the request.
3452TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:553453 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303454 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3455 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553456 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303457}
3458
3459TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:553460 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303461 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3462 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553463 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303464}
3465
3466TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:553467 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303468 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3469 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553470 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303471}
3472
3473// The following 3 tests check that the network delegate can cancel a request
3474// asynchronously in various stages of the request.
3475TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:553476 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303477 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3478 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553479 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303480}
3481
3482TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:553483 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303484 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3485 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553486 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303487}
3488
3489TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:553490 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303491 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3492 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553493 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303494}
3495
[email protected]4c76d7c2011-04-15 19:14:123496// Tests that the network delegate can block and redirect a request to a new
3497// URL.
3498TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:553499 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123500
3501 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303502 BlockingNetworkDelegate network_delegate(
3503 BlockingNetworkDelegate::AUTO_CALLBACK);
3504 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553505 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:123506 network_delegate.set_redirect_url(redirect_url);
3507
[email protected]d5a4dd62012-05-23 01:41:043508 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553509 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503510
[email protected]4c76d7c2011-04-15 19:14:123511 {
tommycli59a63432015-11-06 00:10:553512 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363513 scoped_ptr<URLRequest> r(
3514 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123515
[email protected]6be6fa92014-08-06 23:44:563516 // Quit after hitting the redirect, so can check the headers.
3517 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193518 r->Start();
[email protected]255620da2013-08-19 13:14:293519 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123520
[email protected]6be6fa92014-08-06 23:44:563521 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193522 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3523 EXPECT_EQ(307, r->GetResponseCode());
3524 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563525 std::string location;
[email protected]f7022f32014-08-21 16:32:193526 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3527 &location));
[email protected]6be6fa92014-08-06 23:44:563528 EXPECT_EQ(redirect_url, GURL(location));
3529
3530 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193531 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563532 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193533 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553534 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273535 EXPECT_EQ(
3536 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553537 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3538 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273539
[email protected]f7022f32014-08-21 16:32:193540 EXPECT_EQ(0, r->status().error());
3541 EXPECT_EQ(redirect_url, r->url());
3542 EXPECT_EQ(original_url, r->original_url());
3543 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123544 EXPECT_EQ(1, network_delegate.created_requests());
3545 EXPECT_EQ(0, network_delegate.destroyed_requests());
3546 }
3547 EXPECT_EQ(1, network_delegate.destroyed_requests());
3548}
3549
[email protected]b813ed72012-04-05 08:21:363550// Tests that the network delegate can block and redirect a request to a new
3551// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3552TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:553553 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:363554
3555 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303556 BlockingNetworkDelegate network_delegate(
3557 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:553558 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:363559 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363560
[email protected]d5a4dd62012-05-23 01:41:043561 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553562 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363563
3564 {
tommycli59a63432015-11-06 00:10:553565 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363566 scoped_ptr<URLRequest> r(
3567 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363568
[email protected]6be6fa92014-08-06 23:44:563569 // Quit after hitting the redirect, so can check the headers.
3570 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193571 r->Start();
[email protected]255620da2013-08-19 13:14:293572 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363573
[email protected]6be6fa92014-08-06 23:44:563574 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193575 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3576 EXPECT_EQ(307, r->GetResponseCode());
3577 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563578 std::string location;
[email protected]f7022f32014-08-21 16:32:193579 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3580 &location));
[email protected]6be6fa92014-08-06 23:44:563581 EXPECT_EQ(redirect_url, GURL(location));
3582
3583 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193584 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563585 base::RunLoop().Run();
3586
[email protected]f7022f32014-08-21 16:32:193587 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553588 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273589 EXPECT_EQ(
3590 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553591 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3592 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193593 EXPECT_EQ(0, r->status().error());
3594 EXPECT_EQ(redirect_url, r->url());
3595 EXPECT_EQ(original_url, r->original_url());
3596 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363597 EXPECT_EQ(1, network_delegate.created_requests());
3598 EXPECT_EQ(0, network_delegate.destroyed_requests());
3599 }
3600 EXPECT_EQ(1, network_delegate.destroyed_requests());
3601}
3602
[email protected]3c5ca8c2011-09-29 01:14:513603// Tests that redirects caused by the network delegate preserve POST data.
3604TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:553605 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:513606
3607 const char kData[] = "hello world";
3608
3609 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303610 BlockingNetworkDelegate network_delegate(
3611 BlockingNetworkDelegate::AUTO_CALLBACK);
3612 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553613 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:513614 network_delegate.set_redirect_url(redirect_url);
3615
[email protected]ef2bf422012-05-11 03:27:093616 TestURLRequestContext context(true);
3617 context.set_network_delegate(&network_delegate);
3618 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513619
3620 {
tommycli59a63432015-11-06 00:10:553621 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363622 scoped_ptr<URLRequest> r(
3623 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193624 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073625 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513626 HttpRequestHeaders headers;
3627 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513628 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193629 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563630
3631 // Quit after hitting the redirect, so can check the headers.
3632 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193633 r->Start();
[email protected]255620da2013-08-19 13:14:293634 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513635
[email protected]6be6fa92014-08-06 23:44:563636 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193637 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3638 EXPECT_EQ(307, r->GetResponseCode());
3639 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563640 std::string location;
[email protected]f7022f32014-08-21 16:32:193641 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3642 &location));
[email protected]6be6fa92014-08-06 23:44:563643 EXPECT_EQ(redirect_url, GURL(location));
3644
3645 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193646 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563647 base::RunLoop().Run();
3648
[email protected]f7022f32014-08-21 16:32:193649 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3650 EXPECT_EQ(0, r->status().error());
3651 EXPECT_EQ(redirect_url, r->url());
3652 EXPECT_EQ(original_url, r->original_url());
3653 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513654 EXPECT_EQ(1, network_delegate.created_requests());
3655 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193656 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513657 EXPECT_EQ(kData, d.data_received());
3658 }
3659 EXPECT_EQ(1, network_delegate.destroyed_requests());
3660}
3661
[email protected]5f714132014-03-26 10:41:163662// Tests that the network delegate can block and redirect a request to a new
3663// URL during OnHeadersReceived.
3664TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:553665 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:163666
3667 TestDelegate d;
3668 BlockingNetworkDelegate network_delegate(
3669 BlockingNetworkDelegate::AUTO_CALLBACK);
3670 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:553671 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:163672 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3673
3674 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553675 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:163676
3677 {
tommycli59a63432015-11-06 00:10:553678 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363679 scoped_ptr<URLRequest> r(
3680 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163681
[email protected]f7022f32014-08-21 16:32:193682 r->Start();
[email protected]5f714132014-03-26 10:41:163683 base::RunLoop().Run();
3684
[email protected]f7022f32014-08-21 16:32:193685 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553686 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273687 EXPECT_EQ(
3688 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553689 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3690 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193691
3692 EXPECT_EQ(OK, r->status().error());
3693 EXPECT_EQ(redirect_url, r->url());
3694 EXPECT_EQ(original_url, r->original_url());
3695 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163696 EXPECT_EQ(2, network_delegate.created_requests());
3697 EXPECT_EQ(0, network_delegate.destroyed_requests());
3698 }
3699 EXPECT_EQ(1, network_delegate.destroyed_requests());
3700}
3701
[email protected]c2911d72011-10-03 22:16:363702// Tests that the network delegate can synchronously complete OnAuthRequired
3703// by taking no action. This indicates that the NetworkDelegate does not want to
3704// handle the challenge, and is passing the buck along to the
3705// URLRequest::Delegate.
3706TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:553707 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363708
3709 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303710 BlockingNetworkDelegate network_delegate(
3711 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363712
[email protected]ef2bf422012-05-11 03:27:093713 TestURLRequestContext context(true);
3714 context.set_network_delegate(&network_delegate);
3715 context.Init();
[email protected]c2911d72011-10-03 22:16:363716
[email protected]f3cf9802011-10-28 18:44:583717 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363718
3719 {
tommycli59a63432015-11-06 00:10:553720 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363721 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193722 r->Start();
[email protected]79e1fd62013-06-20 06:50:043723
[email protected]255620da2013-08-19 13:14:293724 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043725
[email protected]f7022f32014-08-21 16:32:193726 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3727 EXPECT_EQ(0, r->status().error());
3728 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043729 EXPECT_TRUE(d.auth_required_called());
3730 EXPECT_EQ(1, network_delegate.created_requests());
3731 EXPECT_EQ(0, network_delegate.destroyed_requests());
3732 }
3733 EXPECT_EQ(1, network_delegate.destroyed_requests());
3734}
3735
3736TEST_F(URLRequestTestHTTP,
3737 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:553738 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:043739
3740 TestDelegate d;
3741 BlockingNetworkDelegate network_delegate(
3742 BlockingNetworkDelegate::SYNCHRONOUS);
3743
3744 TestURLRequestContext context(true);
3745 context.set_network_delegate(&network_delegate);
3746 context.Init();
3747
3748 d.set_credentials(AuthCredentials(kUser, kSecret));
3749
3750 {
tommycli59a63432015-11-06 00:10:553751 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363752 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193753 r->Start();
[email protected]79e1fd62013-06-20 06:50:043754
3755 {
3756 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193757 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043758 EXPECT_FALSE(headers.HasHeader("Authorization"));
3759 }
3760
[email protected]255620da2013-08-19 13:14:293761 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363762
[email protected]f7022f32014-08-21 16:32:193763 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3764 EXPECT_EQ(0, r->status().error());
3765 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363766 EXPECT_TRUE(d.auth_required_called());
3767 EXPECT_EQ(1, network_delegate.created_requests());
3768 EXPECT_EQ(0, network_delegate.destroyed_requests());
3769 }
3770 EXPECT_EQ(1, network_delegate.destroyed_requests());
3771}
3772
3773// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403774// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363775TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:553776 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363777
3778 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303779 BlockingNetworkDelegate network_delegate(
3780 BlockingNetworkDelegate::SYNCHRONOUS);
3781 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363782 network_delegate.set_auth_retval(
3783 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3784
[email protected]f3cf9802011-10-28 18:44:583785 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363786
[email protected]ef2bf422012-05-11 03:27:093787 TestURLRequestContext context(true);
3788 context.set_network_delegate(&network_delegate);
3789 context.Init();
[email protected]c2911d72011-10-03 22:16:363790
3791 {
tommycli59a63432015-11-06 00:10:553792 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363793 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193794 r->Start();
[email protected]255620da2013-08-19 13:14:293795 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363796
[email protected]f7022f32014-08-21 16:32:193797 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3798 EXPECT_EQ(0, r->status().error());
3799 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363800 EXPECT_FALSE(d.auth_required_called());
3801 EXPECT_EQ(1, network_delegate.created_requests());
3802 EXPECT_EQ(0, network_delegate.destroyed_requests());
3803 }
3804 EXPECT_EQ(1, network_delegate.destroyed_requests());
3805}
3806
[email protected]79e1fd62013-06-20 06:50:043807// Same as above, but also tests that GetFullRequestHeaders returns the proper
3808// headers (for the first or second request) when called at the proper times.
3809TEST_F(URLRequestTestHTTP,
3810 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:553811 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:043812
3813 TestDelegate d;
3814 BlockingNetworkDelegate network_delegate(
3815 BlockingNetworkDelegate::SYNCHRONOUS);
3816 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3817 network_delegate.set_auth_retval(
3818 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3819
3820 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3821
3822 TestURLRequestContext context(true);
3823 context.set_network_delegate(&network_delegate);
3824 context.Init();
3825
3826 {
tommycli59a63432015-11-06 00:10:553827 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363828 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193829 r->Start();
[email protected]255620da2013-08-19 13:14:293830 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043831
[email protected]f7022f32014-08-21 16:32:193832 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3833 EXPECT_EQ(0, r->status().error());
3834 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043835 EXPECT_FALSE(d.auth_required_called());
3836 EXPECT_EQ(1, network_delegate.created_requests());
3837 EXPECT_EQ(0, network_delegate.destroyed_requests());
3838
3839 {
3840 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193841 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043842 EXPECT_TRUE(headers.HasHeader("Authorization"));
3843 }
3844 }
3845 EXPECT_EQ(1, network_delegate.destroyed_requests());
3846}
3847
[email protected]c2911d72011-10-03 22:16:363848// Tests that the network delegate can synchronously complete OnAuthRequired
3849// by cancelling authentication.
3850TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:553851 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363852
3853 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303854 BlockingNetworkDelegate network_delegate(
3855 BlockingNetworkDelegate::SYNCHRONOUS);
3856 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363857 network_delegate.set_auth_retval(
3858 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3859
[email protected]ef2bf422012-05-11 03:27:093860 TestURLRequestContext context(true);
3861 context.set_network_delegate(&network_delegate);
3862 context.Init();
[email protected]c2911d72011-10-03 22:16:363863
3864 {
tommycli59a63432015-11-06 00:10:553865 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363866 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193867 r->Start();
[email protected]255620da2013-08-19 13:14:293868 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363869
[email protected]f7022f32014-08-21 16:32:193870 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3871 EXPECT_EQ(OK, r->status().error());
3872 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363873 EXPECT_FALSE(d.auth_required_called());
3874 EXPECT_EQ(1, network_delegate.created_requests());
3875 EXPECT_EQ(0, network_delegate.destroyed_requests());
3876 }
3877 EXPECT_EQ(1, network_delegate.destroyed_requests());
3878}
3879
3880// Tests that the network delegate can asynchronously complete OnAuthRequired
3881// by taking no action. This indicates that the NetworkDelegate does not want
3882// to handle the challenge, and is passing the buck along to the
3883// URLRequest::Delegate.
3884TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:553885 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363886
3887 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303888 BlockingNetworkDelegate network_delegate(
3889 BlockingNetworkDelegate::AUTO_CALLBACK);
3890 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363891
[email protected]ef2bf422012-05-11 03:27:093892 TestURLRequestContext context(true);
3893 context.set_network_delegate(&network_delegate);
3894 context.Init();
[email protected]c2911d72011-10-03 22:16:363895
[email protected]f3cf9802011-10-28 18:44:583896 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363897
3898 {
tommycli59a63432015-11-06 00:10:553899 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363900 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193901 r->Start();
[email protected]255620da2013-08-19 13:14:293902 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363903
[email protected]f7022f32014-08-21 16:32:193904 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3905 EXPECT_EQ(0, r->status().error());
3906 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363907 EXPECT_TRUE(d.auth_required_called());
3908 EXPECT_EQ(1, network_delegate.created_requests());
3909 EXPECT_EQ(0, network_delegate.destroyed_requests());
3910 }
3911 EXPECT_EQ(1, network_delegate.destroyed_requests());
3912}
3913
3914// Tests that the network delegate can asynchronously complete OnAuthRequired
3915// by setting credentials.
3916TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:553917 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363918
3919 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303920 BlockingNetworkDelegate network_delegate(
3921 BlockingNetworkDelegate::AUTO_CALLBACK);
3922 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363923 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363924 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3925
[email protected]f3cf9802011-10-28 18:44:583926 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363927 network_delegate.set_auth_credentials(auth_credentials);
3928
[email protected]ef2bf422012-05-11 03:27:093929 TestURLRequestContext context(true);
3930 context.set_network_delegate(&network_delegate);
3931 context.Init();
[email protected]c2911d72011-10-03 22:16:363932
3933 {
tommycli59a63432015-11-06 00:10:553934 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363935 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193936 r->Start();
[email protected]255620da2013-08-19 13:14:293937 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363938
[email protected]f7022f32014-08-21 16:32:193939 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3940 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:363941
[email protected]f7022f32014-08-21 16:32:193942 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363943 EXPECT_FALSE(d.auth_required_called());
3944 EXPECT_EQ(1, network_delegate.created_requests());
3945 EXPECT_EQ(0, network_delegate.destroyed_requests());
3946 }
3947 EXPECT_EQ(1, network_delegate.destroyed_requests());
3948}
3949
3950// Tests that the network delegate can asynchronously complete OnAuthRequired
3951// by cancelling authentication.
3952TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:553953 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363954
3955 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303956 BlockingNetworkDelegate network_delegate(
3957 BlockingNetworkDelegate::AUTO_CALLBACK);
3958 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363959 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363960 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3961
[email protected]ef2bf422012-05-11 03:27:093962 TestURLRequestContext context(true);
3963 context.set_network_delegate(&network_delegate);
3964 context.Init();
[email protected]c2911d72011-10-03 22:16:363965
3966 {
tommycli59a63432015-11-06 00:10:553967 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363968 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193969 r->Start();
[email protected]255620da2013-08-19 13:14:293970 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363971
[email protected]f7022f32014-08-21 16:32:193972 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3973 EXPECT_EQ(OK, r->status().error());
3974 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363975 EXPECT_FALSE(d.auth_required_called());
3976 EXPECT_EQ(1, network_delegate.created_requests());
3977 EXPECT_EQ(0, network_delegate.destroyed_requests());
3978 }
3979 EXPECT_EQ(1, network_delegate.destroyed_requests());
3980}
3981
[email protected]9045b8822012-01-13 20:35:353982// Tests that we can handle when a network request was canceled while we were
3983// waiting for the network delegate.
3984// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3985TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:553986 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:353987
3988 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303989 BlockingNetworkDelegate network_delegate(
3990 BlockingNetworkDelegate::USER_CALLBACK);
3991 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353992
[email protected]ef2bf422012-05-11 03:27:093993 TestURLRequestContext context(true);
3994 context.set_network_delegate(&network_delegate);
3995 context.Init();
[email protected]9045b8822012-01-13 20:35:353996
3997 {
[email protected]f7022f32014-08-21 16:32:193998 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553999 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354000
[email protected]f7022f32014-08-21 16:32:194001 r->Start();
[email protected]255620da2013-08-19 13:14:294002 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304003 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4004 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354005 EXPECT_EQ(0, network_delegate.completed_requests());
4006 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194007 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354008 // Ensure that network delegate is notified.
4009 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194010 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4011 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354012 EXPECT_EQ(1, network_delegate.created_requests());
4013 EXPECT_EQ(0, network_delegate.destroyed_requests());
4014 }
4015 EXPECT_EQ(1, network_delegate.destroyed_requests());
4016}
4017
4018// Tests that we can handle when a network request was canceled while we were
4019// waiting for the network delegate.
4020// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
4021TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554022 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354023
4024 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304025 BlockingNetworkDelegate network_delegate(
4026 BlockingNetworkDelegate::USER_CALLBACK);
4027 network_delegate.set_block_on(
4028 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354029
[email protected]ef2bf422012-05-11 03:27:094030 TestURLRequestContext context(true);
4031 context.set_network_delegate(&network_delegate);
4032 context.Init();
[email protected]9045b8822012-01-13 20:35:354033
4034 {
[email protected]f7022f32014-08-21 16:32:194035 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554036 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354037
[email protected]f7022f32014-08-21 16:32:194038 r->Start();
[email protected]255620da2013-08-19 13:14:294039 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304040 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4041 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354042 EXPECT_EQ(0, network_delegate.completed_requests());
4043 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194044 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354045 // Ensure that network delegate is notified.
4046 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194047 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4048 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354049 EXPECT_EQ(1, network_delegate.created_requests());
4050 EXPECT_EQ(0, network_delegate.destroyed_requests());
4051 }
4052 EXPECT_EQ(1, network_delegate.destroyed_requests());
4053}
4054
4055// Tests that we can handle when a network request was canceled while we were
4056// waiting for the network delegate.
4057// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4058TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554059 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354060
4061 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304062 BlockingNetworkDelegate network_delegate(
4063 BlockingNetworkDelegate::USER_CALLBACK);
4064 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354065
[email protected]ef2bf422012-05-11 03:27:094066 TestURLRequestContext context(true);
4067 context.set_network_delegate(&network_delegate);
4068 context.Init();
[email protected]9045b8822012-01-13 20:35:354069
4070 {
[email protected]f7022f32014-08-21 16:32:194071 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554072 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354073
[email protected]f7022f32014-08-21 16:32:194074 r->Start();
[email protected]255620da2013-08-19 13:14:294075 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304076 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4077 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354078 EXPECT_EQ(0, network_delegate.completed_requests());
4079 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194080 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354081 // Ensure that network delegate is notified.
4082 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194083 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4084 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354085 EXPECT_EQ(1, network_delegate.created_requests());
4086 EXPECT_EQ(0, network_delegate.destroyed_requests());
4087 }
4088 EXPECT_EQ(1, network_delegate.destroyed_requests());
4089}
4090
4091// Tests that we can handle when a network request was canceled while we were
4092// waiting for the network delegate.
4093// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024094TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554095 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354096
4097 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304098 BlockingNetworkDelegate network_delegate(
4099 BlockingNetworkDelegate::USER_CALLBACK);
4100 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354101
[email protected]ef2bf422012-05-11 03:27:094102 TestURLRequestContext context(true);
4103 context.set_network_delegate(&network_delegate);
4104 context.Init();
[email protected]9045b8822012-01-13 20:35:354105
4106 {
[email protected]f7022f32014-08-21 16:32:194107 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554108 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354109
[email protected]f7022f32014-08-21 16:32:194110 r->Start();
[email protected]255620da2013-08-19 13:14:294111 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304112 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4113 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354114 EXPECT_EQ(0, network_delegate.completed_requests());
4115 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194116 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354117 // Ensure that network delegate is notified.
4118 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194119 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4120 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354121 EXPECT_EQ(1, network_delegate.created_requests());
4122 EXPECT_EQ(0, network_delegate.destroyed_requests());
4123 }
4124 EXPECT_EQ(1, network_delegate.destroyed_requests());
4125}
4126
tommycli59a63432015-11-06 00:10:554127namespace {
4128
4129scoped_ptr<test_server::HttpResponse> HandleServerAuthConnect(
4130 const test_server::HttpRequest& request) {
4131 if (request.headers.find("Host") == request.headers.end() ||
4132 request.headers.at("Host") != "www.server-auth.com" ||
4133 request.method != test_server::METHOD_CONNECT) {
4134 return nullptr;
4135 }
4136
4137 scoped_ptr<test_server::BasicHttpResponse> http_response(
4138 new test_server::BasicHttpResponse);
4139 http_response->set_code(HTTP_UNAUTHORIZED);
4140 http_response->AddCustomHeader("WWW-Authenticate",
4141 "Basic realm=\"WallyWorld\"");
4142 return http_response.Pass();
4143}
4144
4145} // namespace
4146
4147// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114148// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554149// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354150TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554151 http_test_server()->RegisterRequestHandler(
4152 base::Bind(&HandleServerAuthConnect));
4153 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114154
[email protected]ceefd7fd2012-11-29 00:36:244155 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044156 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554157 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504158
[email protected]dc651782009-02-14 01:45:084159 TestDelegate d;
4160 {
[email protected]f7022f32014-08-21 16:32:194161 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364162 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084163
[email protected]f7022f32014-08-21 16:32:194164 r->Start();
4165 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084166
[email protected]255620da2013-08-19 13:14:294167 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084168
[email protected]f7022f32014-08-21 16:32:194169 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:154170 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:194171 EXPECT_TRUE(r->proxy_server().IsEmpty());
4172 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:084173 }
4174}
4175
[email protected]b89290212009-08-14 22:37:354176TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554177 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114178
initial.commit586acc5fe2008-07-26 22:42:524179 TestDelegate d;
4180 {
[email protected]f7022f32014-08-21 16:32:194181 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554182 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524183
[email protected]f7022f32014-08-21 16:32:194184 r->Start();
4185 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524186
[email protected]255620da2013-08-19 13:14:294187 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524188
4189 EXPECT_EQ(1, d.response_started_count());
4190 EXPECT_FALSE(d.received_data_before_response());
4191 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554192 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194193 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554194 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194195 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164196
[email protected]9e743cd2010-03-16 07:03:534197 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524198 }
initial.commit586acc5fe2008-07-26 22:42:524199}
4200
[email protected]263163f2012-06-14 22:40:344201// This test has the server send a large number of cookies to the client.
4202// To ensure that no number of cookies causes a crash, a galloping binary
4203// search is used to estimate that maximum number of cookies that are accepted
4204// by the browser. Beyond the maximum number, the request will fail with
4205// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304206#if defined(OS_WIN)
4207// http://crbug.com/177916
4208#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4209#else
4210#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4211#endif // defined(OS_WIN)
4212TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554213 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344214
4215 int lower_bound = 0;
4216 int upper_bound = 1;
4217
4218 // Double the number of cookies until the response header limits are
4219 // exceeded.
4220 while (DoManyCookiesRequest(upper_bound)) {
4221 lower_bound = upper_bound;
4222 upper_bound *= 2;
4223 ASSERT_LT(upper_bound, 1000000);
4224 }
4225
pkasting6b68a162014-12-01 22:10:294226 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344227 if (tolerance < 2)
4228 tolerance = 2;
4229
4230 // Perform a binary search to find the highest possible number of cookies,
4231 // within the desired tolerance.
4232 while (upper_bound - lower_bound >= tolerance) {
4233 int num_cookies = (lower_bound + upper_bound) / 2;
4234
4235 if (DoManyCookiesRequest(num_cookies))
4236 lower_bound = num_cookies;
4237 else
4238 upper_bound = num_cookies;
4239 }
4240 // Success: the test did not crash.
4241}
4242
[email protected]b89290212009-08-14 22:37:354243TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554244 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114245
initial.commit586acc5fe2008-07-26 22:42:524246 TestDelegate d;
4247 {
[email protected]f7022f32014-08-21 16:32:194248 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554249 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524250
[email protected]f7022f32014-08-21 16:32:194251 r->Start();
4252 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524253
[email protected]255620da2013-08-19 13:14:294254 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524255
4256 EXPECT_EQ(1, d.response_started_count());
4257 EXPECT_FALSE(d.received_data_before_response());
4258 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554259 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194260 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554261 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194262 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524263 }
[email protected]5d7b373e2009-09-02 07:19:034264}
4265
[email protected]79e1fd62013-06-20 06:50:044266TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554267 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044268
4269 TestDelegate d;
4270 {
tommycli59a63432015-11-06 00:10:554271 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:364272 scoped_ptr<URLRequest> r(
4273 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044274
4275 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194276 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044277
[email protected]f7022f32014-08-21 16:32:194278 r->Start();
4279 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044280
[email protected]255620da2013-08-19 13:14:294281 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044282
4283 EXPECT_EQ(1, d.response_started_count());
4284 EXPECT_FALSE(d.received_data_before_response());
4285 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554286 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194287 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554288 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194289 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044290
4291 EXPECT_TRUE(d.have_full_request_headers());
4292 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4293 }
4294}
4295
[email protected]58e32bb2013-01-21 18:23:254296TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554297 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254298
4299 TestDelegate d;
4300 {
[email protected]f7022f32014-08-21 16:32:194301 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554302 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254303
[email protected]f7022f32014-08-21 16:32:194304 r->Start();
4305 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254306
[email protected]255620da2013-08-19 13:14:294307 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254308
4309 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194310 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254311 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4312
4313 EXPECT_EQ(1, d.response_started_count());
4314 EXPECT_FALSE(d.received_data_before_response());
4315 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554316 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194317 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554318 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194319 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254320 }
4321}
4322
tommycli59a63432015-11-06 00:10:554323// TODO(svaldez): Update tests to use EmbeddedTestServer.
4324#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394325TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:554326 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
4327 SpawnedTestServer::kLocalhost,
4328 base::FilePath(kTestFilePath));
4329
4330 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:394331
4332 // Parameter that specifies the Content-Length field in the response:
4333 // C - Compressed length.
4334 // U - Uncompressed length.
4335 // L - Large length (larger than both C & U).
4336 // M - Medium length (between C & U).
4337 // S - Small length (smaller than both C & U).
4338 const char test_parameters[] = "CULMS";
4339 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4340 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444341 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394342 // S has too little data, but we seem to accept it.
4343 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374344 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394345
4346 for (int i = 0; i < num_tests ; i++) {
4347 TestDelegate d;
4348 {
tommycli59a63432015-11-06 00:10:554349 std::string test_file = base::StringPrintf(
4350 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394351
[email protected]ceefd7fd2012-11-29 00:36:244352 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094353 TestURLRequestContext context(true);
4354 context.set_network_delegate(&network_delegate);
4355 context.Init();
[email protected]87a09a92011-07-14 15:50:504356
[email protected]f7022f32014-08-21 16:32:194357 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554358 test_server.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194359 r->Start();
4360 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394361
[email protected]255620da2013-08-19 13:14:294362 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394363
4364 EXPECT_EQ(1, d.response_started_count());
4365 EXPECT_FALSE(d.received_data_before_response());
4366 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194367 << " status = " << r->status().status()
4368 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394369 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194370 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394371 << " Parameter = \"" << test_file << "\"";
4372 } else {
[email protected]f7022f32014-08-21 16:32:194373 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4374 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394375 << " Parameter = \"" << test_file << "\"";
4376 }
4377 }
4378 }
4379}
tommycli59a63432015-11-06 00:10:554380#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394381
tbansala1caf9612015-06-01 20:24:184382TEST_F(URLRequestTestHTTP, NetworkQualityEstimator) {
tommycli59a63432015-11-06 00:10:554383 ASSERT_TRUE(http_test_server()->Start());
tbansalea2fb8c2015-05-22 22:23:004384 // Enable requests to local host to be used for network quality estimation.
tbansalb177b5392015-06-25 11:13:024385 std::map<std::string, std::string> variation_params;
tbansal1c92d5b2015-08-14 20:14:434386 NetworkQualityEstimator estimator(scoped_ptr<net::ExternalEstimateProvider>(),
4387 variation_params, true, true);
tbansalea2fb8c2015-05-22 22:23:004388
4389 TestDelegate d;
4390 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4391 TestURLRequestContext context(true);
4392 context.set_network_quality_estimator(&estimator);
4393 context.set_network_delegate(&network_delegate);
4394 context.Init();
4395
tommycli59a63432015-11-06 00:10:554396 std::string url = "/defaultresponse";
tbansalea2fb8c2015-05-22 22:23:004397
tommycli59a63432015-11-06 00:10:554398 scoped_ptr<URLRequest> r(context.CreateRequest(
4399 http_test_server()->GetURL(url), DEFAULT_PRIORITY, &d));
tbansalea2fb8c2015-05-22 22:23:004400 r->Start();
4401
4402 base::RunLoop().Run();
4403
tbansal9533b6f2015-08-11 22:06:084404 base::TimeDelta rtt;
4405 int32_t kbps;
4406 EXPECT_TRUE(estimator.GetRTTEstimate(&rtt));
4407 EXPECT_TRUE(estimator.GetDownlinkThroughputKbpsEstimate(&kbps));
4408 EXPECT_GE(rtt, base::TimeDelta());
4409 EXPECT_LT(rtt, base::TimeDelta::Max());
4410 EXPECT_GT(kbps, 0);
tbansalea2fb8c2015-05-22 22:23:004411
4412 // Verify that histograms are not populated. They should populate only when
4413 // there is a change in ConnectionType.
4414 base::HistogramTester histogram_tester;
4415 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 0);
4416 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 0);
4417
4418 NetworkChangeNotifier::NotifyObserversOfConnectionTypeChangeForTests(
4419 NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI);
4420 base::MessageLoop::current()->RunUntilIdle();
4421 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 1);
4422 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 1);
4423}
4424
[email protected]58e32bb2013-01-21 18:23:254425TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:554426 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254427
tommycli59a63432015-11-06 00:10:554428 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454429 GURL original_url =
tommycli59a63432015-11-06 00:10:554430 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254431 TestDelegate d;
davidben151423e2015-03-23 18:48:364432 scoped_ptr<URLRequest> req(
4433 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194434 req->Start();
[email protected]255620da2013-08-19 13:14:294435 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254436
4437 EXPECT_EQ(1, d.response_started_count());
4438 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194439 EXPECT_EQ(destination_url, req->url());
4440 EXPECT_EQ(original_url, req->original_url());
4441 ASSERT_EQ(2U, req->url_chain().size());
4442 EXPECT_EQ(original_url, req->url_chain()[0]);
4443 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254444
4445 LoadTimingInfo load_timing_info_before_redirect;
4446 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4447 &load_timing_info_before_redirect));
4448 TestLoadTimingNotReused(load_timing_info_before_redirect,
4449 CONNECT_TIMING_HAS_DNS_TIMES);
4450
4451 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194452 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254453 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4454
4455 // Check that a new socket was used on redirect, since the server does not
4456 // supposed keep-alive sockets, and that the times before the redirect are
4457 // before the ones recorded for the second request.
4458 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4459 load_timing_info.socket_log_id);
4460 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4461 load_timing_info.connect_timing.connect_start);
4462}
4463
[email protected]8f1ac082011-04-19 21:14:134464TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:554465 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:134466
tommycli59a63432015-11-06 00:10:554467 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454468 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:554469 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
4470 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
4471 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:134472 TestDelegate d;
davidben151423e2015-03-23 18:48:364473 scoped_ptr<URLRequest> req(
4474 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194475 req->Start();
[email protected]255620da2013-08-19 13:14:294476 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134477
4478 EXPECT_EQ(1, d.response_started_count());
4479 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194480 EXPECT_EQ(destination_url, req->url());
4481 EXPECT_EQ(original_url, req->original_url());
4482 ASSERT_EQ(3U, req->url_chain().size());
4483 EXPECT_EQ(original_url, req->url_chain()[0]);
4484 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4485 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134486}
4487
[email protected]abe1c4a2013-10-25 19:28:514488// First and second pieces of information logged by delegates to URLRequests.
4489const char kFirstDelegateInfo[] = "Wonderful delegate";
4490const char kSecondDelegateInfo[] = "Exciting delegate";
4491
4492// Logs delegate information to a URLRequest. The first string is logged
4493// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4494// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4495// another asynchronous call is used to clear the delegate information
4496// before calling a callback. The object then deletes itself.
4497class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4498 public:
4499 typedef base::Callback<void()> Callback;
4500
4501 // Each time delegate information is added to the URLRequest, the resulting
4502 // load state is checked. The expected load state after each request is
4503 // passed in as an argument.
4504 static void Run(URLRequest* url_request,
4505 LoadState expected_first_load_state,
4506 LoadState expected_second_load_state,
4507 LoadState expected_third_load_state,
4508 const Callback& callback) {
4509 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4510 url_request,
4511 expected_first_load_state,
4512 expected_second_load_state,
4513 expected_third_load_state,
4514 callback);
4515 logger->Start();
4516 }
4517
4518 // Checks that the log entries, starting with log_position, contain the
4519 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4520 // recorded. Returns the index of entry after the expected number of
4521 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464522 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514523 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514524 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4525 if (log_position + 3 >= entries.size()) {
4526 ADD_FAILURE() << "Not enough log entries";
4527 return entries.size();
4528 }
4529 std::string delegate_info;
4530 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4531 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4532 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4533 &delegate_info));
4534 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4535
4536 ++log_position;
4537 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4538 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4539
4540 ++log_position;
4541 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4542 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4543 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4544 &delegate_info));
4545 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4546
4547 ++log_position;
4548 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4549 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4550
4551 return log_position + 1;
4552 }
4553
[email protected]1826a402014-01-08 15:40:484554 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4555 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464556 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4557 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484558 log_position =
4559 ExpectLogContainsSomewhereAfter(entries,
4560 log_position,
4561 NetLog::TYPE_URL_REQUEST_DELEGATE,
4562 NetLog::PHASE_BEGIN);
4563 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4564 entries[log_position + 1].type);
4565 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4566 return log_position + 1;
4567 }
4568
[email protected]abe1c4a2013-10-25 19:28:514569 private:
4570 friend class base::RefCounted<AsyncDelegateLogger>;
4571
4572 AsyncDelegateLogger(URLRequest* url_request,
4573 LoadState expected_first_load_state,
4574 LoadState expected_second_load_state,
4575 LoadState expected_third_load_state,
4576 const Callback& callback)
4577 : url_request_(url_request),
4578 expected_first_load_state_(expected_first_load_state),
4579 expected_second_load_state_(expected_second_load_state),
4580 expected_third_load_state_(expected_third_load_state),
4581 callback_(callback) {
4582 }
4583
4584 ~AsyncDelegateLogger() {}
4585
4586 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534587 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514588 LoadStateWithParam load_state = url_request_->GetLoadState();
4589 EXPECT_EQ(expected_first_load_state_, load_state.state);
4590 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454591 base::ThreadTaskRunnerHandle::Get()->PostTask(
4592 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514593 }
4594
4595 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534596 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514597 LoadStateWithParam load_state = url_request_->GetLoadState();
4598 EXPECT_EQ(expected_second_load_state_, load_state.state);
4599 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4600 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4601 } else {
4602 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4603 }
skyostil4891b25b2015-06-11 11:43:454604 base::ThreadTaskRunnerHandle::Get()->PostTask(
4605 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514606 }
4607
4608 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534609 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514610 LoadStateWithParam load_state = url_request_->GetLoadState();
4611 EXPECT_EQ(expected_third_load_state_, load_state.state);
4612 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084613 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514614 callback_.Run();
4615 }
4616
4617 URLRequest* url_request_;
4618 const int expected_first_load_state_;
4619 const int expected_second_load_state_;
4620 const int expected_third_load_state_;
4621 const Callback callback_;
4622
4623 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4624};
4625
4626// NetworkDelegate that logs delegate information before a request is started,
4627// before headers are sent, when headers are read, and when auth information
4628// is requested. Uses AsyncDelegateLogger.
4629class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4630 public:
4631 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204632 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514633
4634 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204635 int OnBeforeURLRequest(URLRequest* request,
4636 const CompletionCallback& callback,
4637 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514638 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4639 return RunCallbackAsynchronously(request, callback);
4640 }
4641
dchengb03027d2014-10-21 12:00:204642 int OnBeforeSendHeaders(URLRequest* request,
4643 const CompletionCallback& callback,
4644 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514645 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4646 return RunCallbackAsynchronously(request, callback);
4647 }
4648
dchengb03027d2014-10-21 12:00:204649 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514650 URLRequest* request,
4651 const CompletionCallback& callback,
4652 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164653 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134654 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164655 TestNetworkDelegate::OnHeadersReceived(request,
4656 callback,
[email protected]abe1c4a2013-10-25 19:28:514657 original_response_headers,
[email protected]5f714132014-03-26 10:41:164658 override_response_headers,
4659 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514660 return RunCallbackAsynchronously(request, callback);
4661 }
4662
dchengb03027d2014-10-21 12:00:204663 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514664 URLRequest* request,
4665 const AuthChallengeInfo& auth_info,
4666 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134667 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514668 AsyncDelegateLogger::Run(
4669 request,
4670 LOAD_STATE_WAITING_FOR_DELEGATE,
4671 LOAD_STATE_WAITING_FOR_DELEGATE,
4672 LOAD_STATE_WAITING_FOR_DELEGATE,
4673 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4674 callback, credentials));
4675 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4676 }
4677
4678 private:
4679 static int RunCallbackAsynchronously(
4680 URLRequest* request,
4681 const CompletionCallback& callback) {
4682 AsyncDelegateLogger::Run(
4683 request,
4684 LOAD_STATE_WAITING_FOR_DELEGATE,
4685 LOAD_STATE_WAITING_FOR_DELEGATE,
4686 LOAD_STATE_WAITING_FOR_DELEGATE,
4687 base::Bind(callback, OK));
4688 return ERR_IO_PENDING;
4689 }
4690
4691 static void SetAuthAndResume(const AuthCallback& callback,
4692 AuthCredentials* credentials) {
4693 *credentials = AuthCredentials(kUser, kSecret);
4694 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4695 }
4696
4697 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4698};
4699
4700// URLRequest::Delegate that logs delegate information when the headers
4701// are received, when each read completes, and during redirects. Uses
4702// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4703//
4704// Inherits from TestDelegate to reuse the TestDelegate code to handle
4705// advancing to the next step in most cases, as well as cancellation.
4706class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4707 public:
4708 enum CancelStage {
4709 NO_CANCEL = 0,
4710 CANCEL_ON_RECEIVED_REDIRECT,
4711 CANCEL_ON_RESPONSE_STARTED,
4712 CANCEL_ON_READ_COMPLETED
4713 };
4714
4715 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4716 : cancel_stage_(cancel_stage) {
4717 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4718 set_cancel_in_received_redirect(true);
4719 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4720 set_cancel_in_response_started(true);
4721 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4722 set_cancel_in_received_data(true);
4723 }
dchengb03027d2014-10-21 12:00:204724 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514725
4726 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204727 void OnReceivedRedirect(URLRequest* request,
4728 const RedirectInfo& redirect_info,
4729 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514730 *defer_redirect = true;
4731 AsyncDelegateLogger::Run(
4732 request,
4733 LOAD_STATE_WAITING_FOR_DELEGATE,
4734 LOAD_STATE_WAITING_FOR_DELEGATE,
4735 LOAD_STATE_WAITING_FOR_DELEGATE,
4736 base::Bind(
4737 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594738 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514739 }
4740
dchengb03027d2014-10-21 12:00:204741 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514742 AsyncDelegateLogger::Run(
4743 request,
4744 LOAD_STATE_WAITING_FOR_DELEGATE,
4745 LOAD_STATE_WAITING_FOR_DELEGATE,
4746 LOAD_STATE_WAITING_FOR_DELEGATE,
4747 base::Bind(
4748 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4749 base::Unretained(this), request));
4750 }
4751
dchengb03027d2014-10-21 12:00:204752 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514753 AsyncDelegateLogger::Run(
4754 request,
4755 LOAD_STATE_IDLE,
4756 LOAD_STATE_IDLE,
4757 LOAD_STATE_IDLE,
4758 base::Bind(
4759 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4760 base::Unretained(this), request, bytes_read));
4761 }
4762
4763 private:
4764 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594765 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514766 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594767 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514768 // FollowDeferredRedirect should not be called after cancellation.
4769 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4770 return;
4771 if (!defer_redirect)
4772 request->FollowDeferredRedirect();
4773 }
4774
4775 void OnResponseStartedLoggingComplete(URLRequest* request) {
4776 // The parent class continues the request.
4777 TestDelegate::OnResponseStarted(request);
4778 }
4779
4780 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4781 // The parent class continues the request.
4782 TestDelegate::OnReadCompleted(request, bytes_read);
4783 }
4784
4785 const CancelStage cancel_stage_;
4786
4787 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4788};
4789
4790// Tests handling of delegate info before a request starts.
4791TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:554792 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:514793
4794 TestDelegate request_delegate;
4795 TestURLRequestContext context(true);
4796 context.set_network_delegate(NULL);
4797 context.set_net_log(&net_log_);
4798 context.Init();
4799
4800 {
davidben151423e2015-03-23 18:48:364801 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:554802 context.CreateRequest(http_test_server()->GetURL("/defaultresponse"),
davidben151423e2015-03-23 18:48:364803 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194804 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514805 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084806 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514807
4808 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194809 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514810 LOAD_STATE_WAITING_FOR_DELEGATE,
4811 LOAD_STATE_WAITING_FOR_DELEGATE,
4812 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194813 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514814
4815 base::RunLoop().Run();
4816
[email protected]f7022f32014-08-21 16:32:194817 EXPECT_EQ(200, r->GetResponseCode());
4818 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514819 }
4820
mmenke43758e62015-05-04 21:09:464821 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514822 net_log_.GetEntries(&entries);
4823 size_t log_position = ExpectLogContainsSomewhereAfter(
4824 entries,
4825 0,
4826 NetLog::TYPE_DELEGATE_INFO,
4827 NetLog::PHASE_BEGIN);
4828
4829 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4830
4831 // Nothing else should add any delegate info to the request.
4832 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4833 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4834}
4835
4836// Tests handling of delegate info from a network delegate.
4837TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:554838 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:514839
4840 TestDelegate request_delegate;
4841 AsyncLoggingNetworkDelegate network_delegate;
4842 TestURLRequestContext context(true);
4843 context.set_network_delegate(&network_delegate);
4844 context.set_net_log(&net_log_);
4845 context.Init();
4846
4847 {
davidben151423e2015-03-23 18:48:364848 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:554849 context.CreateRequest(http_test_server()->GetURL("/simple.html"),
davidben151423e2015-03-23 18:48:364850 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194851 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514852 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084853 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514854
[email protected]f7022f32014-08-21 16:32:194855 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514856 base::RunLoop().Run();
4857
[email protected]f7022f32014-08-21 16:32:194858 EXPECT_EQ(200, r->GetResponseCode());
4859 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514860 EXPECT_EQ(1, network_delegate.created_requests());
4861 EXPECT_EQ(0, network_delegate.destroyed_requests());
4862 }
4863 EXPECT_EQ(1, network_delegate.destroyed_requests());
4864
4865 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464866 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514867 net_log_.GetEntries(&entries);
4868 for (size_t i = 0; i < 3; ++i) {
4869 log_position = ExpectLogContainsSomewhereAfter(
4870 entries,
4871 log_position + 1,
4872 NetLog::TYPE_URL_REQUEST_DELEGATE,
4873 NetLog::PHASE_BEGIN);
4874
4875 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4876 log_position + 1);
4877
4878 ASSERT_LT(log_position, entries.size());
4879 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4880 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484881
4882 if (i == 1) {
4883 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4884 entries, log_position + 1);
4885 }
[email protected]abe1c4a2013-10-25 19:28:514886 }
4887
4888 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4889 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4890}
4891
4892// Tests handling of delegate info from a network delegate in the case of an
4893// HTTP redirect.
4894TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:554895 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:514896
4897 TestDelegate request_delegate;
4898 AsyncLoggingNetworkDelegate network_delegate;
4899 TestURLRequestContext context(true);
4900 context.set_network_delegate(&network_delegate);
4901 context.set_net_log(&net_log_);
4902 context.Init();
4903
4904 {
[email protected]f7022f32014-08-21 16:32:194905 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554906 http_test_server()->GetURL("/server-redirect?simple.html"),
4907 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194908 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514909 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084910 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514911
[email protected]f7022f32014-08-21 16:32:194912 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514913 base::RunLoop().Run();
4914
[email protected]f7022f32014-08-21 16:32:194915 EXPECT_EQ(200, r->GetResponseCode());
4916 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514917 EXPECT_EQ(2, network_delegate.created_requests());
4918 EXPECT_EQ(0, network_delegate.destroyed_requests());
4919 }
4920 EXPECT_EQ(1, network_delegate.destroyed_requests());
4921
4922 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464923 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514924 net_log_.GetEntries(&entries);
4925 // The NetworkDelegate logged information in OnBeforeURLRequest,
4926 // OnBeforeSendHeaders, and OnHeadersReceived.
4927 for (size_t i = 0; i < 3; ++i) {
4928 log_position = ExpectLogContainsSomewhereAfter(
4929 entries,
4930 log_position + 1,
4931 NetLog::TYPE_URL_REQUEST_DELEGATE,
4932 NetLog::PHASE_BEGIN);
4933
4934 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4935 log_position + 1);
4936
4937 ASSERT_LT(log_position, entries.size());
4938 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4939 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484940
4941 if (i == 1) {
4942 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4943 entries, log_position + 1);
4944 }
[email protected]abe1c4a2013-10-25 19:28:514945 }
4946
4947 // The URLRequest::Delegate then gets informed about the redirect.
4948 log_position = ExpectLogContainsSomewhereAfter(
4949 entries,
4950 log_position + 1,
4951 NetLog::TYPE_URL_REQUEST_DELEGATE,
4952 NetLog::PHASE_BEGIN);
4953
4954 // The NetworkDelegate logged information in the same three events as before.
4955 for (size_t i = 0; i < 3; ++i) {
4956 log_position = ExpectLogContainsSomewhereAfter(
4957 entries,
4958 log_position + 1,
4959 NetLog::TYPE_URL_REQUEST_DELEGATE,
4960 NetLog::PHASE_BEGIN);
4961
4962 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4963 log_position + 1);
4964
4965 ASSERT_LT(log_position, entries.size());
4966 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4967 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4968 }
4969
4970 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4971 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4972}
4973
4974// Tests handling of delegate info from a network delegate in the case of HTTP
4975// AUTH.
4976TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:554977 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:514978
4979 TestDelegate request_delegate;
4980 AsyncLoggingNetworkDelegate network_delegate;
4981 TestURLRequestContext context(true);
4982 context.set_network_delegate(&network_delegate);
4983 context.set_net_log(&net_log_);
4984 context.Init();
4985
4986 {
davidben151423e2015-03-23 18:48:364987 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:554988 context.CreateRequest(http_test_server()->GetURL("/auth-basic"),
davidben151423e2015-03-23 18:48:364989 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194990 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514991 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084992 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514993
[email protected]f7022f32014-08-21 16:32:194994 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514995 base::RunLoop().Run();
4996
[email protected]f7022f32014-08-21 16:32:194997 EXPECT_EQ(200, r->GetResponseCode());
4998 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514999 EXPECT_EQ(1, network_delegate.created_requests());
5000 EXPECT_EQ(0, network_delegate.destroyed_requests());
5001 }
5002 EXPECT_EQ(1, network_delegate.destroyed_requests());
5003
5004 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465005 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515006 net_log_.GetEntries(&entries);
5007 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
5008 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
5009 // OnBeforeURLRequest and OnBeforeSendHeaders.
5010 for (size_t i = 0; i < 6; ++i) {
5011 log_position = ExpectLogContainsSomewhereAfter(
5012 entries,
5013 log_position + 1,
5014 NetLog::TYPE_URL_REQUEST_DELEGATE,
5015 NetLog::PHASE_BEGIN);
5016
5017 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5018 log_position + 1);
5019
5020 ASSERT_LT(log_position, entries.size());
5021 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5022 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485023
5024 if (i == 1) {
5025 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5026 entries, log_position + 1);
5027 }
[email protected]abe1c4a2013-10-25 19:28:515028 }
5029
5030 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5031 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5032}
5033
tommycli59a63432015-11-06 00:10:555034// TODO(svaldez): Update tests to use EmbeddedTestServer.
5035#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515036// Tests handling of delegate info from a URLRequest::Delegate.
5037TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555038 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
5039 SpawnedTestServer::kLocalhost,
5040 base::FilePath(kTestFilePath));
5041
5042 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515043
5044 AsyncLoggingUrlRequestDelegate request_delegate(
5045 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5046 TestURLRequestContext context(true);
5047 context.set_network_delegate(NULL);
5048 context.set_net_log(&net_log_);
5049 context.Init();
5050
5051 {
5052 // A chunked response with delays between chunks is used to make sure that
5053 // attempts by the URLRequest delegate to log information while reading the
5054 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485055 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515056 // that it occurs.
[email protected]f7022f32014-08-21 16:32:195057 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555058 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365059 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195060 LoadStateWithParam load_state = r->GetLoadState();
5061 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515062 base::RunLoop().Run();
5063
[email protected]f7022f32014-08-21 16:32:195064 EXPECT_EQ(200, r->GetResponseCode());
5065 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515066 }
5067
mmenke43758e62015-05-04 21:09:465068 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515069 net_log_.GetEntries(&entries);
5070
[email protected]1826a402014-01-08 15:40:485071 size_t log_position = 0;
5072
5073 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5074 entries, log_position);
5075
[email protected]abe1c4a2013-10-25 19:28:515076 // The delegate info should only have been logged on header complete. Other
5077 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:485078 log_position =
5079 ExpectLogContainsSomewhereAfter(entries,
5080 log_position + 1,
5081 NetLog::TYPE_URL_REQUEST_DELEGATE,
5082 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515083
5084 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5085 log_position + 1);
5086
5087 ASSERT_LT(log_position, entries.size());
5088 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5089 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5090
5091 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5092 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5093 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5094 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5095}
tommycli59a63432015-11-06 00:10:555096#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515097
5098// Tests handling of delegate info from a URLRequest::Delegate in the case of
5099// an HTTP redirect.
5100TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555101 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515102
5103 AsyncLoggingUrlRequestDelegate request_delegate(
5104 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5105 TestURLRequestContext context(true);
5106 context.set_network_delegate(NULL);
5107 context.set_net_log(&net_log_);
5108 context.Init();
5109
5110 {
[email protected]f7022f32014-08-21 16:32:195111 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555112 http_test_server()->GetURL("/server-redirect?simple.html"),
5113 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195114 LoadStateWithParam load_state = r->GetLoadState();
5115 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515116 base::RunLoop().Run();
5117
[email protected]f7022f32014-08-21 16:32:195118 EXPECT_EQ(200, r->GetResponseCode());
5119 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515120 }
5121
mmenke43758e62015-05-04 21:09:465122 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515123 net_log_.GetEntries(&entries);
5124
5125 // Delegate info should only have been logged in OnReceivedRedirect and
5126 // OnResponseStarted.
5127 size_t log_position = 0;
5128 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485129 if (i == 0) {
5130 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5131 entries, log_position) + 1;
5132 }
5133
[email protected]abe1c4a2013-10-25 19:28:515134 log_position = ExpectLogContainsSomewhereAfter(
5135 entries,
5136 log_position,
5137 NetLog::TYPE_URL_REQUEST_DELEGATE,
5138 NetLog::PHASE_BEGIN);
5139
5140 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5141 log_position + 1);
5142
5143 ASSERT_LT(log_position, entries.size());
5144 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5145 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5146 }
5147
5148 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5149 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5150 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5151 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5152}
5153
5154// Tests handling of delegate info from a URLRequest::Delegate in the case of
5155// an HTTP redirect, with cancellation at various points.
5156TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555157 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515158
5159 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5160 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5161 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5162 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5163 };
5164
5165 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5166 ++test_case) {
5167 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5168 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:515169 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:515170 context.set_network_delegate(NULL);
5171 context.set_net_log(&net_log);
5172 context.Init();
5173
5174 {
[email protected]f7022f32014-08-21 16:32:195175 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555176 http_test_server()->GetURL("/server-redirect?simple.html"),
5177 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195178 LoadStateWithParam load_state = r->GetLoadState();
5179 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515180 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195181 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515182 }
5183
mmenke43758e62015-05-04 21:09:465184 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515185 net_log.GetEntries(&entries);
5186
5187 // Delegate info is always logged in both OnReceivedRedirect and
5188 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5189 // OnResponseStarted delegate call is after cancellation, but logging is
5190 // still currently supported in that call.
5191 size_t log_position = 0;
5192 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485193 if (i == 0) {
5194 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5195 entries, log_position) + 1;
5196 }
5197
[email protected]abe1c4a2013-10-25 19:28:515198 log_position = ExpectLogContainsSomewhereAfter(
5199 entries,
5200 log_position,
5201 NetLog::TYPE_URL_REQUEST_DELEGATE,
5202 NetLog::PHASE_BEGIN);
5203
5204 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5205 log_position + 1);
5206
5207 ASSERT_LT(log_position, entries.size());
5208 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5209 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5210 }
5211
5212 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5213 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5214 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5215 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5216 }
5217}
5218
[email protected]847c0fa92012-11-06 16:37:425219namespace {
5220
5221const char kExtraHeader[] = "Allow-Snafu";
5222const char kExtraValue[] = "fubar";
5223
5224class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205225 void OnReceivedRedirect(URLRequest* request,
5226 const RedirectInfo& redirect_info,
5227 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595228 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425229 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5230 }
5231};
5232
5233} // namespace
5234
5235TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555236 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425237
tommycli59a63432015-11-06 00:10:555238 GURL destination_url =
5239 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5240 GURL original_url =
5241 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425242 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:365243 scoped_ptr<URLRequest> req(
5244 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195245 req->Start();
[email protected]255620da2013-08-19 13:14:295246 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425247
5248 std::string value;
[email protected]f7022f32014-08-21 16:32:195249 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425250 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5251 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195252 EXPECT_FALSE(req->is_pending());
5253 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425254 EXPECT_EQ(kExtraValue, d.data_received());
5255}
5256
[email protected]251a1b92012-11-13 11:01:095257namespace {
5258
5259const char kExtraHeaderToRemove[] = "To-Be-Removed";
5260
5261class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205262 void OnReceivedRedirect(URLRequest* request,
5263 const RedirectInfo& redirect_info,
5264 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595265 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095266 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5267 }
5268};
5269
5270} // namespace
5271
5272TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555273 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095274
tommycli59a63432015-11-06 00:10:555275 GURL destination_url = http_test_server()->GetURL(
5276 "/echoheader?" + std::string(kExtraHeaderToRemove));
5277 GURL original_url =
5278 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095279 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:365280 scoped_ptr<URLRequest> req(
5281 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195282 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5283 req->Start();
[email protected]255620da2013-08-19 13:14:295284 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095285
5286 std::string value;
[email protected]f7022f32014-08-21 16:32:195287 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095288 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195289 EXPECT_FALSE(req->is_pending());
5290 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095291 EXPECT_EQ("None", d.data_received());
5292}
5293
[email protected]316c1e5e2012-09-12 15:17:445294TEST_F(URLRequestTestHTTP, CancelTest) {
5295 TestDelegate d;
5296 {
[email protected]f7022f32014-08-21 16:32:195297 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365298 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445299
[email protected]f7022f32014-08-21 16:32:195300 r->Start();
5301 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445302
[email protected]f7022f32014-08-21 16:32:195303 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445304
[email protected]255620da2013-08-19 13:14:295305 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445306
5307 // We expect to receive OnResponseStarted even though the request has been
5308 // cancelled.
5309 EXPECT_EQ(1, d.response_started_count());
5310 EXPECT_EQ(0, d.bytes_received());
5311 EXPECT_FALSE(d.received_data_before_response());
5312 }
5313}
5314
5315TEST_F(URLRequestTestHTTP, CancelTest2) {
tommycli59a63432015-11-06 00:10:555316 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445317
5318 TestDelegate d;
5319 {
[email protected]f7022f32014-08-21 16:32:195320 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555321 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445322
5323 d.set_cancel_in_response_started(true);
5324
[email protected]f7022f32014-08-21 16:32:195325 r->Start();
5326 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445327
[email protected]255620da2013-08-19 13:14:295328 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445329
5330 EXPECT_EQ(1, d.response_started_count());
5331 EXPECT_EQ(0, d.bytes_received());
5332 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195333 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445334 }
5335}
5336
5337TEST_F(URLRequestTestHTTP, CancelTest3) {
tommycli59a63432015-11-06 00:10:555338 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445339
5340 TestDelegate d;
5341 {
[email protected]f7022f32014-08-21 16:32:195342 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555343 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445344
5345 d.set_cancel_in_received_data(true);
5346
[email protected]f7022f32014-08-21 16:32:195347 r->Start();
5348 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445349
[email protected]255620da2013-08-19 13:14:295350 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445351
5352 EXPECT_EQ(1, d.response_started_count());
5353 // There is no guarantee about how much data was received
5354 // before the cancel was issued. It could have been 0 bytes,
5355 // or it could have been all the bytes.
5356 // EXPECT_EQ(0, d.bytes_received());
5357 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195358 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445359 }
5360}
5361
5362TEST_F(URLRequestTestHTTP, CancelTest4) {
tommycli59a63432015-11-06 00:10:555363 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445364
5365 TestDelegate d;
5366 {
[email protected]f7022f32014-08-21 16:32:195367 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555368 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445369
[email protected]f7022f32014-08-21 16:32:195370 r->Start();
5371 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445372
5373 // The request will be implicitly canceled when it is destroyed. The
5374 // test delegate must not post a quit message when this happens because
5375 // this test doesn't actually have a message loop. The quit message would
5376 // get put on this thread's message queue and the next test would exit
5377 // early, causing problems.
5378 d.set_quit_on_complete(false);
5379 }
5380 // expect things to just cleanup properly.
5381
5382 // we won't actually get a received reponse here because we've never run the
5383 // message loop
5384 EXPECT_FALSE(d.received_data_before_response());
5385 EXPECT_EQ(0, d.bytes_received());
5386}
5387
5388TEST_F(URLRequestTestHTTP, CancelTest5) {
tommycli59a63432015-11-06 00:10:555389 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445390
5391 // populate cache
5392 {
5393 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195394 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555395 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195396 r->Start();
[email protected]255620da2013-08-19 13:14:295397 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195398 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445399 }
5400
5401 // cancel read from cache (see bug 990242)
5402 {
5403 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195404 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555405 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195406 r->Start();
5407 r->Cancel();
[email protected]255620da2013-08-19 13:14:295408 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445409
[email protected]f7022f32014-08-21 16:32:195410 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445411 EXPECT_EQ(1, d.response_started_count());
5412 EXPECT_EQ(0, d.bytes_received());
5413 EXPECT_FALSE(d.received_data_before_response());
5414 }
5415}
5416
5417TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:555418 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445419 HTTPUploadDataOperationTest("POST");
5420}
5421
5422TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:555423 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445424 HTTPUploadDataOperationTest("PUT");
5425}
5426
5427TEST_F(URLRequestTestHTTP, PostEmptyTest) {
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("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195434 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445435
[email protected]f7022f32014-08-21 16:32:195436 r->Start();
5437 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445438
[email protected]255620da2013-08-19 13:14:295439 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445440
[email protected]329b68b2012-11-14 17:54:275441 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195442 << "request failed: " << r->status().status()
5443 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445444
5445 EXPECT_FALSE(d.received_data_before_response());
5446 EXPECT_TRUE(d.data_received().empty());
5447 }
5448}
5449
5450TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:555451 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445452
5453 TestDelegate d;
5454 {
[email protected]f7022f32014-08-21 16:32:195455 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555456 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195457 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445458
[email protected]6cdfd7f2013-02-08 20:40:155459 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445460 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025461 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445462
olli.raula6df48b2a2015-11-26 07:40:225463 std::vector<scoped_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445464
[email protected]6cdfd7f2013-02-08 20:40:155465 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445466 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475467 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445468 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
olli.raula6df48b2a2015-11-26 07:40:225469 element_readers.push_back(make_scoped_ptr(
skyostil4891b25b2015-06-11 11:43:455470 new UploadFileElementReader(base::ThreadTaskRunnerHandle::Get().get(),
olli.raula6df48b2a2015-11-26 07:40:225471 path, 0, kuint64max, base::Time())));
mmenkecbc2b712014-10-09 20:29:075472 r->set_upload(make_scoped_ptr<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225473 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:445474
[email protected]f7022f32014-08-21 16:32:195475 r->Start();
5476 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445477
[email protected]255620da2013-08-19 13:14:295478 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445479
pkasting6b68a162014-12-01 22:10:295480 int64 size64 = 0;
5481 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5482 ASSERT_LE(size64, std::numeric_limits<int>::max());
5483 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175484 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445485
[email protected]7600d0b2013-12-08 21:43:305486 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445487
[email protected]329b68b2012-11-14 17:54:275488 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195489 << "request failed: " << r->status().status()
5490 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445491
5492 EXPECT_FALSE(d.received_data_before_response());
5493
[email protected]329b68b2012-11-14 17:54:275494 EXPECT_EQ(size, d.bytes_received());
5495 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445496 }
5497}
5498
[email protected]999dd8c2013-11-12 06:45:545499TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:555500 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:545501
5502 TestDelegate d;
5503 {
[email protected]f7022f32014-08-21 16:32:195504 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555505 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195506 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545507
olli.raula6df48b2a2015-11-26 07:40:225508 std::vector<scoped_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:545509
olli.raula6df48b2a2015-11-26 07:40:225510 element_readers.push_back(make_scoped_ptr(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455511 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545512 base::FilePath(FILE_PATH_LITERAL(
5513 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
olli.raula6df48b2a2015-11-26 07:40:225514 0, kuint64max, base::Time())));
mmenkecbc2b712014-10-09 20:29:075515 r->set_upload(make_scoped_ptr<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225516 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:545517
[email protected]f7022f32014-08-21 16:32:195518 r->Start();
5519 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545520
5521 base::RunLoop().Run();
5522
[email protected]999dd8c2013-11-12 06:45:545523 EXPECT_TRUE(d.request_failed());
5524 EXPECT_FALSE(d.received_data_before_response());
5525 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195526 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5527 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545528 }
5529}
5530
[email protected]316c1e5e2012-09-12 15:17:445531TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:555532 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445533
5534 TestDelegate d;
5535 {
[email protected]f7022f32014-08-21 16:32:195536 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555537 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195538 r->EnableChunkedUpload();
5539 r->set_method("POST");
5540 AddChunksToUpload(r.get());
5541 r->Start();
5542 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445543
[email protected]255620da2013-08-19 13:14:295544 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445545
[email protected]f7022f32014-08-21 16:32:195546 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445547 }
5548}
5549
[email protected]329b68b2012-11-14 17:54:275550TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:555551 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:275552
5553 TestDelegate d;
5554 {
[email protected]f7022f32014-08-21 16:32:195555 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555556 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195557 r->EnableChunkedUpload();
5558 r->set_method("POST");
5559 r->Start();
5560 EXPECT_TRUE(r->is_pending());
5561 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295562 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275563
[email protected]f7022f32014-08-21 16:32:195564 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275565 }
5566}
5567
[email protected]316c1e5e2012-09-12 15:17:445568TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:555569 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445570
5571 TestDelegate d;
5572 {
[email protected]f7022f32014-08-21 16:32:195573 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555574 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195575 r->EnableChunkedUpload();
5576 r->set_method("POST");
5577 r->Start();
5578 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445579
[email protected]255620da2013-08-19 13:14:295580 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195581 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295582 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445583
[email protected]f7022f32014-08-21 16:32:195584 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445585 }
5586}
5587
5588TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:555589 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445590
5591 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195592 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555593 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195594 req->Start();
[email protected]255620da2013-08-19 13:14:295595 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445596
[email protected]f7022f32014-08-21 16:32:195597 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445598
5599 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195600 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445601
5602 std::string header;
5603 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5604 EXPECT_EQ("private", header);
5605
5606 header.clear();
5607 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5608 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5609
5610 // The response has two "X-Multiple-Entries" headers.
5611 // This verfies our output has them concatenated together.
5612 header.clear();
5613 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5614 EXPECT_EQ("a, b", header);
5615}
5616
tommycli59a63432015-11-06 00:10:555617// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
5618// security state. (see http://crbug.com/550977).
5619#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:465620TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:555621 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5622 https_test_server.SetSSLConfig(
5623 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5624 https_test_server.ServeFilesFromSourceDirectory(
5625 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465626 ASSERT_TRUE(https_test_server.Start());
5627
tommycli59a63432015-11-06 00:10:555628 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:465629 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195630 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555631 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195632 request->Start();
[email protected]255620da2013-08-19 13:14:295633 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465634
5635 TransportSecurityState* security_state =
5636 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405637 TransportSecurityState::STSState sts_state;
5638 TransportSecurityState::PKPState pkp_state;
5639 EXPECT_TRUE(
5640 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5641 EXPECT_FALSE(
5642 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5643 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5644 sts_state.upgrade_mode);
5645 EXPECT_TRUE(sts_state.include_subdomains);
5646 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:035647#if defined(OS_ANDROID)
5648 // Android's CertVerifyProc does not (yet) handle pins.
5649#else
martijnc0d6b622015-06-30 19:14:405650 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035651#endif
[email protected]37fd55fb2013-06-29 13:13:275652}
5653
estarka5da76702015-04-09 04:00:165654TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555655 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5656 https_test_server.ServeFilesFromSourceDirectory(
5657 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165658 ASSERT_TRUE(https_test_server.Start());
5659 // Make sure this test fails if the test server is changed to not
5660 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555661 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5662 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165663
5664 TestDelegate d;
5665 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555666 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:165667 request->Start();
5668 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:165669 TransportSecurityState* security_state =
5670 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405671 TransportSecurityState::STSState sts_state;
5672 EXPECT_FALSE(
5673 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165674}
5675
mathpc992e602015-10-21 20:34:035676// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5677// reject HPKP headers, and a test setting only HPKP headers will fail (no
5678// PKPState present because header rejected).
5679#if defined(OS_ANDROID)
5680#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5681#define MAYBE_ProcessPKPAndSendReport DISABLED_ProcessPKPAndSendReport
5682#define MAYBE_ProcessPKPReportOnly DISABLED_ProcessPKPReportOnly
5683#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5684 DISABLED_ProcessPKPReportOnlyWithNoViolation
5685#else
5686#define MAYBE_ProcessPKP ProcessPKP
5687#define MAYBE_ProcessPKPAndSendReport ProcessPKPAndSendReport
5688#define MAYBE_ProcessPKPReportOnly ProcessPKPReportOnly
5689#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5690 ProcessPKPReportOnlyWithNoViolation
5691#endif
5692
estark06e0dac2015-08-07 21:56:015693namespace {
5694const char kHPKPReportUri[] = "https://hpkp-report.test";
5695} // namespace
5696
[email protected]37fd55fb2013-06-29 13:13:275697// Tests that enabling HPKP on a domain does not affect the HSTS
5698// validity/expiration.
mathpc992e602015-10-21 20:34:035699TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estark06e0dac2015-08-07 21:56:015700 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555701 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5702 https_test_server.SetSSLConfig(
5703 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5704 https_test_server.ServeFilesFromSourceDirectory(
5705 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275706 ASSERT_TRUE(https_test_server.Start());
5707
tommycli59a63432015-11-06 00:10:555708 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165709
[email protected]37fd55fb2013-06-29 13:13:275710 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195711 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555712 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195713 request->Start();
[email protected]255620da2013-08-19 13:14:295714 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275715 TransportSecurityState* security_state =
5716 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405717 TransportSecurityState::STSState sts_state;
5718 TransportSecurityState::PKPState pkp_state;
5719 EXPECT_FALSE(
5720 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5721 EXPECT_TRUE(
5722 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5723 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
5724 sts_state.upgrade_mode);
5725 EXPECT_FALSE(sts_state.include_subdomains);
5726 EXPECT_FALSE(pkp_state.include_subdomains);
5727 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:015728 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:405729 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:465730}
5731
estark06e0dac2015-08-07 21:56:015732// Tests that reports get sent on HPKP violations when a report-uri is set.
mathpc992e602015-10-21 20:34:035733TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:015734 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555735 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5736 https_test_server.SetSSLConfig(
5737 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5738 https_test_server.ServeFilesFromSourceDirectory(
5739 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015740 ASSERT_TRUE(https_test_server.Start());
5741
tommycli59a63432015-11-06 00:10:555742 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015743
5744 // Set up a pin for |test_server_hostname|.
5745 TransportSecurityState security_state;
5746 const base::Time current_time(base::Time::Now());
5747 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
5748 HashValueVector hashes;
5749 HashValue hash1;
5750 HashValue hash2;
5751 // The values here don't matter, as long as they are different from
5752 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:445753 ASSERT_TRUE(
5754 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
5755 ASSERT_TRUE(
5756 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:015757 hashes.push_back(hash1);
5758 hashes.push_back(hash2);
5759 security_state.AddHPKP(test_server_hostname, expiry,
5760 false, /* include subdomains */
5761 hashes, report_uri);
5762
5763 MockCertificateReportSender mock_report_sender;
5764 security_state.SetReportSender(&mock_report_sender);
5765
5766 // Set up a MockCertVerifier to trigger a violation of the previously
5767 // set pin.
5768 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5769 ASSERT_TRUE(cert);
5770
5771 MockCertVerifier cert_verifier;
5772 CertVerifyResult verify_result;
5773 verify_result.verified_cert = cert;
5774 verify_result.is_issued_by_known_root = true;
5775 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:445776 ASSERT_TRUE(
5777 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:015778 verify_result.public_key_hashes.push_back(hash3);
5779 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5780
5781 TestNetworkDelegate network_delegate;
5782 TestURLRequestContext context(true);
5783 context.set_transport_security_state(&security_state);
5784 context.set_network_delegate(&network_delegate);
5785 context.set_cert_verifier(&cert_verifier);
5786 context.Init();
5787
5788 // Now send a request to trigger the violation.
5789 TestDelegate d;
5790 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555791 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
estark06e0dac2015-08-07 21:56:015792 violating_request->Start();
5793 base::RunLoop().Run();
5794
5795 // Check that a report was sent.
5796 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5797 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5798 scoped_ptr<base::Value> value(
5799 base::JSONReader::Read(mock_report_sender.latest_report()));
5800 ASSERT_TRUE(value);
5801 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
5802 base::DictionaryValue* report_dict;
5803 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
5804 std::string report_hostname;
5805 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
5806 EXPECT_EQ(test_server_hostname, report_hostname);
5807}
5808
5809// Tests that reports get sent on requests with
5810// Public-Key-Pins-Report-Only headers.
mathpc992e602015-10-21 20:34:035811TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnly) {
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));
estark06e0dac2015-08-07 21:56:015818 ASSERT_TRUE(https_test_server.Start());
5819
tommycli59a63432015-11-06 00:10:555820 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015821
5822 TransportSecurityState security_state;
5823 MockCertificateReportSender mock_report_sender;
5824 security_state.SetReportSender(&mock_report_sender);
5825
5826 // Set up a MockCertVerifier to violate the pin in the Report-Only
5827 // header.
5828 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5829 ASSERT_TRUE(cert);
5830
5831 MockCertVerifier cert_verifier;
5832 CertVerifyResult verify_result;
5833 verify_result.verified_cert = cert;
5834 verify_result.is_issued_by_known_root = true;
5835 HashValue hash;
5836 // This value doesn't matter, as long as it is different from the pins
5837 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:445838 ASSERT_TRUE(
5839 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:015840 verify_result.public_key_hashes.push_back(hash);
5841 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5842
5843 TestNetworkDelegate network_delegate;
5844 TestURLRequestContext context(true);
5845 context.set_transport_security_state(&security_state);
5846 context.set_network_delegate(&network_delegate);
5847 context.set_cert_verifier(&cert_verifier);
5848 context.Init();
5849
5850 // Now send a request to trigger the violation.
5851 TestDelegate d;
5852 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555853 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:015854 DEFAULT_PRIORITY, &d));
5855 violating_request->Start();
5856 base::RunLoop().Run();
5857
5858 // Check that a report was sent.
5859 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5860 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5861 scoped_ptr<base::Value> value(
5862 base::JSONReader::Read(mock_report_sender.latest_report()));
5863 ASSERT_TRUE(value);
5864 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
5865 base::DictionaryValue* report_dict;
5866 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
5867 std::string report_hostname;
5868 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
5869 EXPECT_EQ(test_server_hostname, report_hostname);
5870}
5871
5872// Tests that reports do not get sent on requests with
5873// Public-Key-Pins-Report-Only headers that don't have pin violations.
mathpc992e602015-10-21 20:34:035874TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:015875 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555876 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5877 https_test_server.SetSSLConfig(
5878 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5879 https_test_server.ServeFilesFromSourceDirectory(
5880 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015881 ASSERT_TRUE(https_test_server.Start());
5882
tommycli59a63432015-11-06 00:10:555883 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015884
5885 TransportSecurityState security_state;
5886 MockCertificateReportSender mock_report_sender;
5887 security_state.SetReportSender(&mock_report_sender);
5888
5889 TestNetworkDelegate network_delegate;
5890 MockCertVerifier mock_cert_verifier;
5891 TestURLRequestContext context(true);
5892 context.set_transport_security_state(&security_state);
5893 context.set_network_delegate(&network_delegate);
5894 context.set_cert_verifier(&mock_cert_verifier);
5895 mock_cert_verifier.set_default_result(OK);
5896 context.Init();
5897
5898 // Now send a request that does not trigger the violation.
5899 TestDelegate d;
5900 scoped_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555901 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:015902 DEFAULT_PRIORITY, &d));
5903 request->Start();
5904 base::RunLoop().Run();
5905
5906 // Check that a report was not sent.
5907 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
5908 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
5909}
5910
estarka5da76702015-04-09 04:00:165911TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555912 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5913 https_test_server.ServeFilesFromSourceDirectory(
5914 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165915 ASSERT_TRUE(https_test_server.Start());
5916 // Make sure this test fails if the test server is changed to not
5917 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555918 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5919 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165920
5921 TestDelegate d;
5922 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555923 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:165924 request->Start();
5925 base::RunLoop().Run();
5926
5927 TransportSecurityState* security_state =
5928 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405929 TransportSecurityState::PKPState pkp_state;
5930 EXPECT_FALSE(
5931 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:165932}
5933
[email protected]242d8562012-10-30 21:20:465934TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:555935 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5936 https_test_server.SetSSLConfig(
5937 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5938 https_test_server.ServeFilesFromSourceDirectory(
5939 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465940 ASSERT_TRUE(https_test_server.Start());
5941
tommycli59a63432015-11-06 00:10:555942 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165943
[email protected]242d8562012-10-30 21:20:465944 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195945 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555946 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
5947 &d));
[email protected]f7022f32014-08-21 16:32:195948 request->Start();
[email protected]255620da2013-08-19 13:14:295949 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465950
5951 // We should have set parameters from the first header, not the second.
5952 TransportSecurityState* security_state =
5953 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405954 TransportSecurityState::STSState sts_state;
5955 EXPECT_TRUE(
5956 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5957 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5958 sts_state.upgrade_mode);
5959 EXPECT_FALSE(sts_state.include_subdomains);
5960 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:465961}
5962
[email protected]9f972ec2013-04-10 20:24:365963TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:555964 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5965 https_test_server.SetSSLConfig(
5966 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5967 https_test_server.ServeFilesFromSourceDirectory(
5968 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:365969 ASSERT_TRUE(https_test_server.Start());
5970
tommycli59a63432015-11-06 00:10:555971 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165972
[email protected]9f972ec2013-04-10 20:24:365973 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195974 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555975 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
5976 &d));
[email protected]f7022f32014-08-21 16:32:195977 request->Start();
[email protected]255620da2013-08-19 13:14:295978 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365979
5980 // We should have set parameters from the first header, not the second.
5981 TransportSecurityState* security_state =
5982 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405983 TransportSecurityState::STSState sts_state;
5984 TransportSecurityState::PKPState pkp_state;
5985 EXPECT_TRUE(
5986 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5987 EXPECT_TRUE(
5988 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5989 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5990 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:035991#if defined(OS_ANDROID)
5992 // Android's CertVerifyProc does not (yet) handle pins.
5993#else
martijnc0d6b622015-06-30 19:14:405994 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035995#endif
martijnc0d6b622015-06-30 19:14:405996 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:365997
[email protected]a165f092013-06-12 16:10:055998 // Even though there is an HSTS header asserting includeSubdomains, it is
5999 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406000 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056001 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406002 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366003}
6004
[email protected]37fd55fb2013-06-29 13:13:276005// Tests that when multiple HPKP headers are present, asserting different
6006// policies, that only the first such policy is processed.
6007TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556008 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6009 https_test_server.SetSSLConfig(
6010 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6011 https_test_server.ServeFilesFromSourceDirectory(
6012 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276013 ASSERT_TRUE(https_test_server.Start());
6014
tommycli59a63432015-11-06 00:10:556015 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166016
[email protected]37fd55fb2013-06-29 13:13:276017 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196018 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556019 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:366020 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196021 request->Start();
[email protected]255620da2013-08-19 13:14:296022 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276023
6024 TransportSecurityState* security_state =
6025 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406026 TransportSecurityState::STSState sts_state;
6027 TransportSecurityState::PKPState pkp_state;
6028 EXPECT_TRUE(
6029 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6030 EXPECT_TRUE(
6031 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6032 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6033 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036034#if defined(OS_ANDROID)
6035 // Android's CertVerifyProc does not (yet) handle pins.
6036#else
martijnc0d6b622015-06-30 19:14:406037 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036038#endif
martijnc0d6b622015-06-30 19:14:406039 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276040
martijnc0d6b622015-06-30 19:14:406041 EXPECT_TRUE(sts_state.include_subdomains);
6042 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276043}
6044
tommycli59a63432015-11-06 00:10:556045#endif // !defined(OS_IOS)
6046
[email protected]316c1e5e2012-09-12 15:17:446047TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:556048 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446049
6050 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196051 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556052 http_test_server()->GetURL("/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366053 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196054 req->Start();
[email protected]255620da2013-08-19 13:14:296055 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446056
6057 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196058 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446059 EXPECT_EQ("text/html", mime_type);
6060
6061 std::string charset;
[email protected]f7022f32014-08-21 16:32:196062 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446063 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196064 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446065}
6066
[email protected]02494ec2014-05-07 15:05:296067TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346068 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346069 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346070 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026071 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346072
6073 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506074 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346075}
6076
[email protected]02494ec2014-05-07 15:05:296077#if !defined(DISABLE_FILE_SUPPORT)
6078TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6079 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6080 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456081 FileProtocolHandler file_protocol_handler(
6082 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296083 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6084
6085 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506086 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296087}
6088
[email protected]588614c22013-08-16 00:09:026089TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:556090 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446091
6092 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196093 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556094 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366095 &d));
[email protected]f7022f32014-08-21 16:32:196096 req->Start();
[email protected]255620da2013-08-19 13:14:296097 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446098
[email protected]f7022f32014-08-21 16:32:196099 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6100 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446101}
[email protected]02494ec2014-05-07 15:05:296102#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446103
[email protected]588614c22013-08-16 00:09:026104TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:556105 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:026106
6107 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196108 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556109 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366110 &d));
[email protected]f7022f32014-08-21 16:32:196111 req->Start();
[email protected]588614c22013-08-16 00:09:026112 base::MessageLoop::current()->Run();
6113
[email protected]f7022f32014-08-21 16:32:196114 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6115 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:026116}
6117
[email protected]316c1e5e2012-09-12 15:17:446118TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:556119 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446120
6121 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196122 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556123 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366124 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196125 req->Start();
[email protected]255620da2013-08-19 13:14:296126 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446127
[email protected]f7022f32014-08-21 16:32:196128 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6129 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446130}
6131
[email protected]e50efea2014-03-24 18:41:006132// Make sure redirects are cached, despite not reading their bodies.
6133TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:556134 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006135 GURL redirect_url =
tommycli59a63432015-11-06 00:10:556136 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:006137
6138 {
6139 TestDelegate d;
davidben151423e2015-03-23 18:48:366140 scoped_ptr<URLRequest> req(
6141 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196142 req->Start();
[email protected]e50efea2014-03-24 18:41:006143 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196144 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006145 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:556146 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006147 }
6148
6149 {
6150 TestDelegate d;
6151 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:366152 scoped_ptr<URLRequest> req(
6153 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196154 req->Start();
[email protected]e50efea2014-03-24 18:41:006155 base::RunLoop().Run();
6156
6157 EXPECT_EQ(1, d.received_redirect_count());
6158 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196159 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006160
[email protected]f7022f32014-08-21 16:32:196161 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006162 base::RunLoop().Run();
6163 EXPECT_EQ(1, d.received_redirect_count());
6164 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196165 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
tommycli59a63432015-11-06 00:10:556166 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006167 }
6168}
6169
6170// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6171// when the headers are read, since the body won't have been read.
6172TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:556173 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006174 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:556175 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:006176
6177 {
6178 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:556179 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:006180 default_network_delegate_.set_redirect_on_headers_received_url(
6181 redirect_to_url);
6182
6183 TestDelegate d;
davidben151423e2015-03-23 18:48:366184 scoped_ptr<URLRequest> req(
6185 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196186 req->Start();
[email protected]e50efea2014-03-24 18:41:006187 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196188 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006189 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196190 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006191 }
6192
6193 {
6194 TestDelegate d;
davidben151423e2015-03-23 18:48:366195 scoped_ptr<URLRequest> req(
6196 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196197 req->Start();
[email protected]e50efea2014-03-24 18:41:006198 base::RunLoop().Run();
6199
[email protected]f7022f32014-08-21 16:32:196200 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6201 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006202 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196203 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006204 }
6205}
6206
[email protected]5f714132014-03-26 10:41:166207// Tests that redirection to an unsafe URL is allowed when it has been marked as
6208// safe.
6209TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:556210 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166211
6212 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6213 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6214 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6215
6216 TestDelegate d;
6217 {
[email protected]f7022f32014-08-21 16:32:196218 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556219 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166220
[email protected]f7022f32014-08-21 16:32:196221 r->Start();
[email protected]5f714132014-03-26 10:41:166222 base::RunLoop().Run();
6223
[email protected]f7022f32014-08-21 16:32:196224 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:166225
[email protected]f7022f32014-08-21 16:32:196226 EXPECT_EQ(2U, r->url_chain().size());
6227 EXPECT_EQ(OK, r->status().error());
6228 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166229 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6230 }
6231}
6232
6233// Tests that a redirect to a different unsafe URL is blocked, even after adding
6234// some other URL to the whitelist.
6235TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:556236 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166237
6238 GURL unsafe_url("data:text/html,something");
6239 GURL different_unsafe_url("data:text/html,something-else");
6240 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6241 default_network_delegate_.set_allowed_unsafe_redirect_url(
6242 different_unsafe_url);
6243
6244 TestDelegate d;
6245 {
[email protected]f7022f32014-08-21 16:32:196246 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556247 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166248
[email protected]f7022f32014-08-21 16:32:196249 r->Start();
[email protected]5f714132014-03-26 10:41:166250 base::RunLoop().Run();
6251
[email protected]f7022f32014-08-21 16:32:196252 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
6253 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:166254 }
6255}
6256
[email protected]5f714132014-03-26 10:41:166257// Redirects from an URL with fragment to an unsafe URL with fragment should
6258// be allowed, and the reference fragment of the target URL should be preserved.
6259TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:556260 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166261
tommycli59a63432015-11-06 00:10:556262 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:166263 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6264 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6265
6266 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6267 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6268
6269 TestDelegate d;
6270 {
davidben151423e2015-03-23 18:48:366271 scoped_ptr<URLRequest> r(
6272 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166273
[email protected]f7022f32014-08-21 16:32:196274 r->Start();
[email protected]5f714132014-03-26 10:41:166275 base::RunLoop().Run();
6276
[email protected]f7022f32014-08-21 16:32:196277 EXPECT_EQ(2U, r->url_chain().size());
6278 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6279 EXPECT_EQ(OK, r->status().error());
6280 EXPECT_EQ(original_url, r->original_url());
6281 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166282 }
6283}
6284
6285// When a delegate has specified a safe redirect URL, but it does not match the
6286// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146287TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:556288 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166289
tommycli59a63432015-11-06 00:10:556290 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166291 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:556292 GURL redirect_url(http_test_server()->GetURL("/target"));
6293 GURL expected_redirect_url(
6294 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166295
6296 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6297 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6298
6299 TestDelegate d;
6300 {
davidben151423e2015-03-23 18:48:366301 scoped_ptr<URLRequest> r(
6302 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166303
[email protected]f7022f32014-08-21 16:32:196304 r->Start();
[email protected]5f714132014-03-26 10:41:166305 base::RunLoop().Run();
6306
[email protected]f7022f32014-08-21 16:32:196307 EXPECT_EQ(2U, r->url_chain().size());
6308 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6309 EXPECT_EQ(OK, r->status().error());
6310 EXPECT_EQ(original_url, r->original_url());
6311 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166312 }
6313}
6314
[email protected]f878230e2014-04-03 15:36:146315// When a delegate has specified a safe redirect URL, assume that the redirect
6316// URL should not be changed. In particular, the reference fragment should not
6317// be modified.
6318TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556319 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146320
tommycli59a63432015-11-06 00:10:556321 GURL original_url(
6322 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:146323 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6324
6325 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6326 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6327
6328 TestDelegate d;
6329 {
davidben151423e2015-03-23 18:48:366330 scoped_ptr<URLRequest> r(
6331 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146332
[email protected]f7022f32014-08-21 16:32:196333 r->Start();
[email protected]f878230e2014-04-03 15:36:146334 base::RunLoop().Run();
6335
[email protected]f7022f32014-08-21 16:32:196336 EXPECT_EQ(2U, r->url_chain().size());
6337 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6338 EXPECT_EQ(OK, r->status().error());
6339 EXPECT_EQ(original_url, r->original_url());
6340 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146341 }
6342}
6343
6344// When a URLRequestRedirectJob is created, the redirection must be followed and
6345// the reference fragment of the target URL must not be modified.
6346TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556347 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146348
tommycli59a63432015-11-06 00:10:556349 GURL original_url(
6350 http_test_server()->GetURL("/original#should-not-be-appended"));
6351 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:146352
6353 TestDelegate d;
davidben151423e2015-03-23 18:48:366354 scoped_ptr<URLRequest> r(
6355 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146356
6357 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196358 r.get(), &default_network_delegate_, redirect_url,
[email protected]f878230e2014-04-03 15:36:146359 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6360 AddTestInterceptor()->set_main_intercept_job(job);
6361
[email protected]f7022f32014-08-21 16:32:196362 r->Start();
[email protected]f878230e2014-04-03 15:36:146363 base::RunLoop().Run();
6364
[email protected]f7022f32014-08-21 16:32:196365 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6366 EXPECT_EQ(OK, r->status().error());
6367 EXPECT_EQ(original_url, r->original_url());
6368 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146369}
6370
[email protected]316c1e5e2012-09-12 15:17:446371TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:556372 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446373
6374 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196375 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556376 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196377 req->SetReferrer("http://user:[email protected]/");
6378 req->Start();
[email protected]255620da2013-08-19 13:14:296379 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446380
6381 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6382}
6383
[email protected]99ecf6e2013-04-10 22:46:136384TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:556385 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136386
6387 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196388 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556389 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196390 req->SetReferrer("http://foo.com/test#fragment");
6391 req->Start();
[email protected]255620da2013-08-19 13:14:296392 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136393
6394 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6395}
6396
6397TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:556398 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136399
6400 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196401 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556402 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196403 req->SetReferrer("http://foo.com/test#fragment");
6404 req->SetReferrer("");
6405 req->Start();
[email protected]255620da2013-08-19 13:14:296406 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136407
6408 EXPECT_EQ(std::string("None"), d.data_received());
6409}
6410
[email protected]1826a402014-01-08 15:40:486411// Defer network start and then resume, checking that the request was a success
6412// and bytes were received.
6413TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556414 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486415
6416 TestDelegate d;
6417 {
6418 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556419 GURL test_url(http_test_server()->GetURL("/echo"));
davidben151423e2015-03-23 18:48:366420 scoped_ptr<URLRequest> req(
6421 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486422
[email protected]f7022f32014-08-21 16:32:196423 req->Start();
[email protected]1826a402014-01-08 15:40:486424 base::RunLoop().Run();
6425
6426 EXPECT_EQ(1, d.received_before_network_start_count());
6427 EXPECT_EQ(0, d.response_started_count());
6428
[email protected]f7022f32014-08-21 16:32:196429 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486430 base::RunLoop().Run();
6431
6432 EXPECT_EQ(1, d.response_started_count());
6433 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196434 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486435 }
6436}
6437
6438// Check that OnBeforeNetworkStart is only called once even if there is a
6439// redirect.
6440TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
tommycli59a63432015-11-06 00:10:556441 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486442
6443 TestDelegate d;
6444 {
6445 d.set_quit_on_redirect(true);
6446 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:196447 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556448 http_test_server()->GetURL("/server-redirect?echo"), DEFAULT_PRIORITY,
6449 &d));
[email protected]1826a402014-01-08 15:40:486450
[email protected]f7022f32014-08-21 16:32:196451 req->Start();
[email protected]1826a402014-01-08 15:40:486452 base::RunLoop().Run();
6453
6454 EXPECT_EQ(1, d.received_before_network_start_count());
6455 EXPECT_EQ(0, d.response_started_count());
6456 EXPECT_EQ(0, d.received_redirect_count());
6457
[email protected]f7022f32014-08-21 16:32:196458 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486459 base::RunLoop().Run();
6460
6461 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196462 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:486463 base::RunLoop().Run();
6464
6465 // Check that the redirect's new network transaction does not get propagated
6466 // to a second OnBeforeNetworkStart() notification.
6467 EXPECT_EQ(1, d.received_before_network_start_count());
6468
6469 EXPECT_EQ(1, d.response_started_count());
6470 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196471 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486472 }
6473}
6474
6475// Cancel the request after learning that the request would use the network.
6476TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556477 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486478
6479 TestDelegate d;
6480 {
6481 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556482 GURL test_url(http_test_server()->GetURL("/echo"));
davidben151423e2015-03-23 18:48:366483 scoped_ptr<URLRequest> req(
6484 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486485
[email protected]f7022f32014-08-21 16:32:196486 req->Start();
[email protected]1826a402014-01-08 15:40:486487 base::RunLoop().Run();
6488
6489 EXPECT_EQ(1, d.received_before_network_start_count());
6490 EXPECT_EQ(0, d.response_started_count());
6491
[email protected]f7022f32014-08-21 16:32:196492 req->Cancel();
[email protected]1826a402014-01-08 15:40:486493 base::RunLoop().Run();
6494
6495 EXPECT_EQ(1, d.response_started_count());
6496 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196497 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:486498 }
6499}
6500
[email protected]316c1e5e2012-09-12 15:17:446501TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:556502 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446503
6504 TestDelegate d;
6505 {
6506 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:196507 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556508 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6509 &d));
[email protected]f7022f32014-08-21 16:32:196510 req->Start();
[email protected]255620da2013-08-19 13:14:296511 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446512
6513 EXPECT_EQ(1, d.response_started_count());
6514 EXPECT_EQ(0, d.bytes_received());
6515 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196516 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446517 }
6518}
6519
6520TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:556521 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446522
6523 TestDelegate d;
6524 {
6525 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556526 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
davidben151423e2015-03-23 18:48:366527 scoped_ptr<URLRequest> req(
6528 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046529
[email protected]f7022f32014-08-21 16:32:196530 req->Start();
[email protected]255620da2013-08-19 13:14:296531 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446532
6533 EXPECT_EQ(1, d.received_redirect_count());
6534
[email protected]f7022f32014-08-21 16:32:196535 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296536 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446537
6538 EXPECT_EQ(1, d.response_started_count());
6539 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196540 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446541
[email protected]6cdfd7f2013-02-08 20:40:156542 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446543 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476544 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446545 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6546
6547 std::string contents;
[email protected]82f84b92013-08-30 18:23:506548 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446549 EXPECT_EQ(contents, d.data_received());
6550 }
6551}
6552
[email protected]79e1fd62013-06-20 06:50:046553TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:556554 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:046555
6556 TestDelegate d;
6557 {
6558 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556559 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
davidben151423e2015-03-23 18:48:366560 scoped_ptr<URLRequest> req(
6561 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046562
6563 EXPECT_FALSE(d.have_full_request_headers());
6564
[email protected]f7022f32014-08-21 16:32:196565 req->Start();
[email protected]255620da2013-08-19 13:14:296566 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046567
6568 EXPECT_EQ(1, d.received_redirect_count());
6569 EXPECT_TRUE(d.have_full_request_headers());
6570 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6571 d.ClearFullRequestHeaders();
6572
[email protected]f7022f32014-08-21 16:32:196573 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296574 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046575
tommycli59a63432015-11-06 00:10:556576 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:046577 EXPECT_EQ(1, d.response_started_count());
6578 EXPECT_TRUE(d.have_full_request_headers());
6579 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6580 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196581 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046582
6583 base::FilePath path;
6584 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476585 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046586 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6587
6588 std::string contents;
[email protected]82f84b92013-08-30 18:23:506589 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046590 EXPECT_EQ(contents, d.data_received());
6591 }
6592}
6593
[email protected]316c1e5e2012-09-12 15:17:446594TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:556595 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446596
6597 TestDelegate d;
6598 {
6599 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196600 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556601 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6602 &d));
[email protected]f7022f32014-08-21 16:32:196603 req->Start();
[email protected]255620da2013-08-19 13:14:296604 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446605
6606 EXPECT_EQ(1, d.received_redirect_count());
6607
[email protected]f7022f32014-08-21 16:32:196608 req->Cancel();
[email protected]255620da2013-08-19 13:14:296609 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446610
6611 EXPECT_EQ(1, d.response_started_count());
6612 EXPECT_EQ(0, d.bytes_received());
6613 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196614 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446615 }
6616}
6617
6618TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:556619 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446620
[email protected]3b23a222013-05-15 21:33:256621 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446622 {
6623 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196624 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556625 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6626 &d));
[email protected]316c1e5e2012-09-12 15:17:446627 HttpRequestHeaders headers;
6628 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196629 req->SetExtraRequestHeaders(headers);
6630 req->Start();
[email protected]255620da2013-08-19 13:14:296631 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256632
6633 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196634 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256635 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446636 }
6637
[email protected]3b23a222013-05-15 21:33:256638 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446639 {
6640 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196641 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556642 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6643 &d));
[email protected]316c1e5e2012-09-12 15:17:446644 HttpRequestHeaders headers;
6645 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196646 req->SetExtraRequestHeaders(headers);
6647 req->Start();
[email protected]255620da2013-08-19 13:14:296648 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446649
[email protected]f7022f32014-08-21 16:32:196650 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256651
6652 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196653 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256654 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446655 }
6656
[email protected]3b23a222013-05-15 21:33:256657 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446658 {
6659 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196660 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556661 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6662 &d));
[email protected]316c1e5e2012-09-12 15:17:446663 HttpRequestHeaders headers;
6664 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196665 req->SetExtraRequestHeaders(headers);
6666 req->Start();
[email protected]255620da2013-08-19 13:14:296667 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446668
[email protected]f7022f32014-08-21 16:32:196669 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256670
6671 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196672 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256673 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446674 }
6675}
6676
6677TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:556678 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446679
6680 // populate the cache
6681 {
6682 TestDelegate d;
6683 d.set_credentials(AuthCredentials(kUser, kSecret));
6684
[email protected]f7022f32014-08-21 16:32:196685 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556686 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196687 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446688
[email protected]255620da2013-08-19 13:14:296689 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446690
6691 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6692 }
6693
6694 // repeat request with end-to-end validation. since auth-basic results in a
6695 // cachable page, we expect this test to result in a 304. in which case, the
6696 // response should be fetched from the cache.
6697 {
6698 TestDelegate d;
6699 d.set_credentials(AuthCredentials(kUser, kSecret));
6700
[email protected]f7022f32014-08-21 16:32:196701 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556702 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196703 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6704 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446705
[email protected]255620da2013-08-19 13:14:296706 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446707
6708 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6709
6710 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196711 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446712 }
6713}
6714
6715// Check that Set-Cookie headers in 401 responses are respected.
6716// http://crbug.com/6450
6717TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:556718 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446719
6720 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:556721 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:446722
6723 // Request a page that will give a 401 containing a Set-Cookie header.
6724 // Verify that when the transaction is restarted, it includes the new cookie.
6725 {
[email protected]ceefd7fd2012-11-29 00:36:246726 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446727 TestURLRequestContext context(true);
6728 context.set_network_delegate(&network_delegate);
6729 context.Init();
6730
6731 TestDelegate d;
6732 d.set_credentials(AuthCredentials(kUser, kSecret));
6733
davidben151423e2015-03-23 18:48:366734 scoped_ptr<URLRequest> r(
6735 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196736 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446737
[email protected]255620da2013-08-19 13:14:296738 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446739
6740 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6741
6742 // Make sure we sent the cookie in the restarted transaction.
6743 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6744 != std::string::npos);
6745 }
6746
6747 // Same test as above, except this time the restart is initiated earlier
6748 // (without user intervention since identity is embedded in the URL).
6749 {
[email protected]ceefd7fd2012-11-29 00:36:246750 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446751 TestURLRequestContext context(true);
6752 context.set_network_delegate(&network_delegate);
6753 context.Init();
6754
6755 TestDelegate d;
6756
6757 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186758 replacements.SetUsernameStr("user2");
6759 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446760 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6761
davidben151423e2015-03-23 18:48:366762 scoped_ptr<URLRequest> r(
6763 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196764 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446765
[email protected]255620da2013-08-19 13:14:296766 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446767
6768 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6769
6770 // Make sure we sent the cookie in the restarted transaction.
6771 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6772 != std::string::npos);
6773 }
6774}
6775
[email protected]58e32bb2013-01-21 18:23:256776// Tests that load timing works as expected with auth and the cache.
6777TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:556778 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:256779
6780 // populate the cache
6781 {
6782 TestDelegate d;
6783 d.set_credentials(AuthCredentials(kUser, kSecret));
6784
[email protected]f7022f32014-08-21 16:32:196785 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556786 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196787 r->Start();
[email protected]58e32bb2013-01-21 18:23:256788
[email protected]255620da2013-08-19 13:14:296789 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256790
6791 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6792
6793 LoadTimingInfo load_timing_info_before_auth;
6794 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6795 &load_timing_info_before_auth));
6796 TestLoadTimingNotReused(load_timing_info_before_auth,
6797 CONNECT_TIMING_HAS_DNS_TIMES);
6798
6799 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196800 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256801 // The test server does not support keep alive sockets, so the second
6802 // request with auth should use a new socket.
6803 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6804 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6805 load_timing_info.socket_log_id);
6806 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6807 load_timing_info.connect_timing.connect_start);
6808 }
6809
[email protected]3b23a222013-05-15 21:33:256810 // Repeat request with end-to-end validation. Since auth-basic results in a
6811 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256812 // response should be fetched from the cache.
6813 {
6814 TestDelegate d;
6815 d.set_credentials(AuthCredentials(kUser, kSecret));
6816
[email protected]f7022f32014-08-21 16:32:196817 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556818 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196819 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6820 r->Start();
[email protected]58e32bb2013-01-21 18:23:256821
[email protected]255620da2013-08-19 13:14:296822 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256823
6824 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6825
6826 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196827 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256828
[email protected]3b23a222013-05-15 21:33:256829 // Since there was a request that went over the wire, the load timing
6830 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256831 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196832 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256833 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256834 }
6835}
6836
[email protected]316c1e5e2012-09-12 15:17:446837// In this test, we do a POST which the server will 302 redirect.
6838// The subsequent transaction should use GET, and should not send the
6839// Content-Type header.
6840// http://code.google.com/p/chromium/issues/detail?id=843
6841TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:556842 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446843
6844 const char kData[] = "hello world";
6845
6846 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196847 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556848 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY,
6849 &d));
[email protected]f7022f32014-08-21 16:32:196850 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076851 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446852
6853 // Set headers (some of which are specific to the POST).
6854 HttpRequestHeaders headers;
6855 headers.AddHeadersFromString(
6856 "Content-Type: multipart/form-data; "
6857 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6858 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6859 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6860 "Accept-Language: en-US,en\r\n"
6861 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6862 "Content-Length: 11\r\n"
6863 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196864 req->SetExtraRequestHeaders(headers);
6865 req->Start();
[email protected]255620da2013-08-19 13:14:296866 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446867
6868 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196869 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446870 EXPECT_EQ("text/html", mime_type);
6871
6872 const std::string& data = d.data_received();
6873
6874 // Check that the post-specific headers were stripped:
6875 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6876 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6877 EXPECT_FALSE(ContainsString(data, "Origin:"));
6878
6879 // These extra request headers should not have been stripped.
6880 EXPECT_TRUE(ContainsString(data, "Accept:"));
6881 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6882 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6883}
6884
jww5fe460ff2015-03-28 00:22:516885// The following tests check that we handle mutating the request for HTTP
6886// redirects as expected.
6887// See https://crbug.com/56373, https://crbug.com/102130, and
6888// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:446889
6890TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:556891 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446892
tommycli59a63432015-11-06 00:10:556893 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:516894 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:556895 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:446896
6897 HTTPRedirectMethodTest(url, "POST", "GET", true);
6898 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6899 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516900
6901 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6902 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6903 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6904 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6905 std::string());
[email protected]316c1e5e2012-09-12 15:17:446906}
6907
6908TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:556909 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446910
tommycli59a63432015-11-06 00:10:556911 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:516912 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:556913 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:446914
6915 HTTPRedirectMethodTest(url, "POST", "GET", true);
6916 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6917 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516918
6919 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6920 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6921 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6922 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6923 std::string());
[email protected]316c1e5e2012-09-12 15:17:446924}
6925
6926TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:556927 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446928
tommycli59a63432015-11-06 00:10:556929 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:516930 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:556931 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:446932
6933 HTTPRedirectMethodTest(url, "POST", "GET", true);
6934 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6935 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516936
6937 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6938 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6939 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6940 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6941 std::string());
[email protected]316c1e5e2012-09-12 15:17:446942}
6943
6944TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:556945 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446946
tommycli59a63432015-11-06 00:10:556947 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:516948 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:556949 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:446950
6951 HTTPRedirectMethodTest(url, "POST", "POST", true);
6952 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6953 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516954
6955 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6956 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6957 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6958 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:446959}
6960
[email protected]0a17aab32014-04-24 03:32:376961TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:556962 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:376963
tommycli59a63432015-11-06 00:10:556964 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:516965 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:556966 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:376967
6968 HTTPRedirectMethodTest(url, "POST", "POST", true);
6969 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6970 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516971
6972 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6973 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6974 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6975 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:376976}
6977
6978// Make sure that 308 responses without bodies are not treated as redirects.
6979// Certain legacy apis that pre-date the response code expect this behavior
6980// (Like Google Drive).
6981TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:556982 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:376983
6984 TestDelegate d;
tommycli59a63432015-11-06 00:10:556985 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:376986
davidben151423e2015-03-23 18:48:366987 scoped_ptr<URLRequest> request(
6988 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:376989
[email protected]f7022f32014-08-21 16:32:196990 request->Start();
[email protected]0a17aab32014-04-24 03:32:376991 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196992 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6993 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:376994 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196995 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:376996 EXPECT_EQ("This is not a redirect.", d.data_received());
6997}
6998
[email protected]f878230e2014-04-03 15:36:146999TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:557000 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147001
tommycli59a63432015-11-06 00:10:557002 GURL original_url(
7003 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
7004 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:147005
7006 TestDelegate d;
7007 {
davidben151423e2015-03-23 18:48:367008 scoped_ptr<URLRequest> r(
7009 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:147010
[email protected]f7022f32014-08-21 16:32:197011 r->Start();
[email protected]f878230e2014-04-03 15:36:147012 base::RunLoop().Run();
7013
[email protected]f7022f32014-08-21 16:32:197014 EXPECT_EQ(2U, r->url_chain().size());
7015 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7016 EXPECT_EQ(OK, r->status().error());
7017 EXPECT_EQ(original_url, r->original_url());
7018 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:147019 }
7020}
7021
[email protected]cba24642014-08-15 20:49:597022TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557023 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597024
tommycli59a63432015-11-06 00:10:557025 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597026 GURL first_party_url("http://example.com");
7027
7028 TestDelegate d;
7029 {
davidben151423e2015-03-23 18:48:367030 scoped_ptr<URLRequest> r(
7031 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197032 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:597033
[email protected]f7022f32014-08-21 16:32:197034 r->Start();
[email protected]cba24642014-08-15 20:49:597035 base::RunLoop().Run();
7036
[email protected]f7022f32014-08-21 16:32:197037 EXPECT_EQ(2U, r->url_chain().size());
7038 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7039 EXPECT_EQ(OK, r->status().error());
7040 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597041 }
7042}
7043
7044TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557045 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597046
tommycli59a63432015-11-06 00:10:557047 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597048 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:557049 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:597050
7051 TestDelegate d;
7052 {
davidben151423e2015-03-23 18:48:367053 scoped_ptr<URLRequest> r(
7054 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197055 r->set_first_party_for_cookies(original_first_party_url);
7056 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597057 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7058
[email protected]f7022f32014-08-21 16:32:197059 r->Start();
[email protected]cba24642014-08-15 20:49:597060 base::RunLoop().Run();
7061
[email protected]f7022f32014-08-21 16:32:197062 EXPECT_EQ(2U, r->url_chain().size());
7063 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7064 EXPECT_EQ(OK, r->status().error());
7065 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597066 }
7067}
7068
[email protected]316c1e5e2012-09-12 15:17:447069TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:557070 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447071
7072 const char kData[] = "hello world";
7073
7074 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197075 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557076 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197077 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077078 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447079 HttpRequestHeaders headers;
7080 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517081 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197082 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447083
7084 URLRequestRedirectJob* job = new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557085 req.get(), &default_network_delegate_,
7086 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097087 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:447088 AddTestInterceptor()->set_main_intercept_job(job);
7089
[email protected]f7022f32014-08-21 16:32:197090 req->Start();
[email protected]255620da2013-08-19 13:14:297091 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197092 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447093}
7094
7095TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:557096 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447097
7098 const char kData[] = "hello world";
7099
7100 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197101 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557102 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197103 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077104 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447105 HttpRequestHeaders headers;
7106 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517107 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197108 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447109
7110 URLRequestRedirectJob* job = new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557111 req.get(), &default_network_delegate_,
7112 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097113 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
7114 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:447115 AddTestInterceptor()->set_main_intercept_job(job);
7116
[email protected]f7022f32014-08-21 16:32:197117 req->Start();
[email protected]255620da2013-08-19 13:14:297118 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197119 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447120 EXPECT_EQ(kData, d.data_received());
7121}
7122
7123// Check that default A-L header is sent.
7124TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557125 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447126
[email protected]8790210c2013-12-02 05:29:537127 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247128 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447129 TestURLRequestContext context(true);
7130 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437131 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447132 context.Init();
7133
7134 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197135 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557136 http_test_server()->GetURL("/echoheader?Accept-Language"),
7137 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197138 req->Start();
[email protected]255620da2013-08-19 13:14:297139 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447140 EXPECT_EQ("en", d.data_received());
7141}
7142
7143// Check that an empty A-L header is not sent. http://crbug.com/77365.
7144TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557145 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447146
[email protected]8790210c2013-12-02 05:29:537147 std::string empty_string; // Avoid most vexing parse on line below.
7148 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247149 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447150 TestURLRequestContext context(true);
7151 context.set_network_delegate(&network_delegate);
7152 context.Init();
7153 // We override the language after initialization because empty entries
7154 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437155 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447156
7157 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197158 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557159 http_test_server()->GetURL("/echoheader?Accept-Language"),
7160 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197161 req->Start();
[email protected]255620da2013-08-19 13:14:297162 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447163 EXPECT_EQ("None", d.data_received());
7164}
7165
7166// Check that if request overrides the A-L header, the default is not appended.
7167// See http://crbug.com/20894
7168TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557169 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447170
7171 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197172 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557173 http_test_server()->GetURL("/echoheader?Accept-Language"),
7174 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447175 HttpRequestHeaders headers;
7176 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197177 req->SetExtraRequestHeaders(headers);
7178 req->Start();
[email protected]255620da2013-08-19 13:14:297179 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447180 EXPECT_EQ(std::string("ru"), d.data_received());
7181}
7182
7183// Check that default A-E header is sent.
7184TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557185 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447186
7187 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197188 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557189 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7190 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447191 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197192 req->SetExtraRequestHeaders(headers);
7193 req->Start();
[email protected]255620da2013-08-19 13:14:297194 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447195 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7196}
7197
7198// Check that if request overrides the A-E header, the default is not appended.
7199// See http://crbug.com/47381
7200TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557201 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447202
7203 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197204 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557205 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7206 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447207 HttpRequestHeaders headers;
7208 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197209 req->SetExtraRequestHeaders(headers);
7210 req->Start();
[email protected]255620da2013-08-19 13:14:297211 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447212 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7213 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7214}
7215
[email protected]84f05432013-03-15 01:00:127216// Check that setting the A-C header sends the proper header.
7217TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:557218 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447219
7220 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197221 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557222 http_test_server()->GetURL("/echoheader?Accept-Charset"),
7223 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447224 HttpRequestHeaders headers;
7225 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197226 req->SetExtraRequestHeaders(headers);
7227 req->Start();
[email protected]255620da2013-08-19 13:14:297228 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447229 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7230}
7231
7232// Check that default User-Agent header is sent.
7233TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:557234 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447235
7236 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197237 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557238 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7239 &d));
[email protected]f7022f32014-08-21 16:32:197240 req->Start();
[email protected]255620da2013-08-19 13:14:297241 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197242 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377243 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447244}
7245
7246// Check that if request overrides the User-Agent header,
7247// the default is not appended.
7248TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:557249 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447250
7251 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197252 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557253 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7254 &d));
[email protected]316c1e5e2012-09-12 15:17:447255 HttpRequestHeaders headers;
7256 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197257 req->SetExtraRequestHeaders(headers);
7258 req->Start();
[email protected]255620da2013-08-19 13:14:297259 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357260 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447261}
7262
[email protected]ee4c30d2012-11-07 15:08:437263// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7264// User-Agent header to be sent but does not send the Accept-Language and
7265// Accept-Charset headers.
7266TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:557267 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:437268
[email protected]ceefd7fd2012-11-29 00:36:247269 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437270 TestURLRequestContext context(true);
7271 context.set_network_delegate(&network_delegate);
7272 context.Init();
7273 // We override the HttpUserAgentSettings after initialization because empty
7274 // entries get overridden by Init().
7275 context.set_http_user_agent_settings(NULL);
7276
7277 struct {
7278 const char* request;
7279 const char* expected_response;
tommycli59a63432015-11-06 00:10:557280 } tests[] = {{"/echoheader?Accept-Language", "None"},
7281 {"/echoheader?Accept-Charset", "None"},
7282 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:437283
viettrungluue4a8b882014-10-16 06:17:387284 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437285 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197286 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557287 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197288 req->Start();
[email protected]255620da2013-08-19 13:14:297289 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437290 EXPECT_EQ(tests[i].expected_response, d.data_received())
7291 << " Request = \"" << tests[i].request << "\"";
7292 }
7293}
7294
[email protected]5033ab82013-03-22 20:17:467295// Make sure that URLRequest passes on its priority updates to
7296// newly-created jobs after the first one.
7297TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:557298 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:467299
7300 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197301 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557302 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197303 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467304
tommycli59a63432015-11-06 00:10:557305 scoped_refptr<URLRequestRedirectJob> redirect_job = new URLRequestRedirectJob(
7306 req.get(), &default_network_delegate_,
7307 http_test_server()->GetURL("/echo"),
7308 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:507309 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:467310
[email protected]f7022f32014-08-21 16:32:197311 req->SetPriority(LOW);
7312 req->Start();
7313 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467314
7315 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:197316 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:507317 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:467318
7319 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297320 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:467321 EXPECT_EQ(LOW, job->priority());
7322}
7323
[email protected]80abdad2014-03-15 00:20:547324// Check that creating a network request while entering/exiting suspend mode
7325// fails as it should. This is the only case where an HttpTransactionFactory
7326// does not return an HttpTransaction.
7327TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7328 // Create a new HttpNetworkLayer that thinks it's suspended.
mmenke2281f3762015-11-02 20:38:177329 scoped_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
7330 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547331 network_layer->OnSuspend();
7332
mmenkebc31a2c2015-10-29 13:44:457333 HttpCache http_cache(network_layer.Pass(),
mmenkee65e7af2015-10-13 17:16:427334 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547335
7336 TestURLRequestContext context(true);
7337 context.set_http_transaction_factory(&http_cache);
7338 context.Init();
7339
7340 TestDelegate d;
davidben151423e2015-03-23 18:48:367341 scoped_ptr<URLRequest> req(
7342 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197343 req->Start();
[email protected]80abdad2014-03-15 00:20:547344 base::RunLoop().Run();
7345
7346 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197347 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7348 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547349}
7350
mmenke2281f3762015-11-02 20:38:177351namespace {
[email protected]80abdad2014-03-15 00:20:547352
mmenke2281f3762015-11-02 20:38:177353// HttpTransactionFactory that synchronously fails to create transactions.
7354class FailingHttpTransactionFactory : public HttpTransactionFactory {
7355 public:
7356 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7357 : network_session_(network_session) {}
7358
7359 ~FailingHttpTransactionFactory() override {}
7360
7361 // HttpTransactionFactory methods:
7362 int CreateTransaction(RequestPriority priority,
7363 scoped_ptr<HttpTransaction>* trans) override {
7364 return ERR_FAILED;
7365 }
7366
7367 HttpCache* GetCache() override { return nullptr; }
7368
7369 HttpNetworkSession* GetSession() override { return network_session_; }
7370
7371 private:
7372 HttpNetworkSession* network_session_;
7373
7374 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7375};
7376
7377} // namespace
7378
7379// Check that when a request that fails to create an HttpTransaction can be
7380// cancelled while the failure notification is pending, and doesn't send two
7381// failure notifications.
7382//
7383// This currently only happens when in suspend mode and there's no cache, but
7384// just use a special HttpTransactionFactory, to avoid depending on those
7385// behaviors.
7386TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7387 FailingHttpTransactionFactory http_transaction_factory(
7388 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547389 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177390 context.set_http_transaction_factory(&http_transaction_factory);
7391 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547392 context.Init();
7393
7394 TestDelegate d;
davidben151423e2015-03-23 18:48:367395 scoped_ptr<URLRequest> req(
7396 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177397 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7398 // try to create an HttpNetworkTransaction synchronously on start).
7399 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197400 req->Start();
mmenke2281f3762015-11-02 20:38:177401 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547402 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177403 // Run pending error task, if there is one.
7404 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547405
7406 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177407 EXPECT_EQ(1, d.response_started_count());
7408 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
7409
7410 // NetworkDelegate should see the cancellation, but not the error.
7411 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7412 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547413}
7414
ttuttlec0c828492015-05-15 01:25:557415TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:557416 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557417
7418 TestDelegate d;
tommycli59a63432015-11-06 00:10:557419 GURL test_url(http_test_server()->GetURL("/"));
ttuttlec0c828492015-05-15 01:25:557420 scoped_ptr<URLRequest> req(
7421 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7422
7423 req->Start();
7424 base::RunLoop().Run();
7425
7426 EXPECT_TRUE(req->response_info().network_accessed);
7427}
7428
7429TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:557430 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557431
7432 // Populate the cache.
7433 TestDelegate d;
7434 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557435 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
ttuttlec0c828492015-05-15 01:25:557436 req->Start();
7437 base::RunLoop().Run();
7438
7439 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7440 EXPECT_TRUE(req->response_info().network_accessed);
7441 EXPECT_FALSE(req->response_info().was_cached);
7442
tommycli59a63432015-11-06 00:10:557443 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
ttuttlec0c828492015-05-15 01:25:557444 DEFAULT_PRIORITY, &d);
7445 req->Start();
7446 base::RunLoop().Run();
7447
7448 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7449 EXPECT_FALSE(req->response_info().network_accessed);
7450 EXPECT_TRUE(req->response_info().was_cached);
7451}
7452
7453TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:557454 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557455
7456 TestDelegate d;
tommycli59a63432015-11-06 00:10:557457 GURL test_url(http_test_server()->GetURL("/"));
ttuttlec0c828492015-05-15 01:25:557458 scoped_ptr<URLRequest> req(
7459 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7460 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7461
7462 req->Start();
7463 base::RunLoop().Run();
7464
7465 EXPECT_FALSE(req->response_info().network_accessed);
7466}
7467
bengr1bf8e942014-11-07 01:36:507468class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7469 public:
7470 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7471 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7472 // tests into the factory tests.
7473 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7474 }
7475
7476 void SetUpFactory() override {
7477 interceptor_ = new MockURLRequestInterceptor();
7478 job_factory_.reset(new URLRequestInterceptingJobFactory(
7479 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
7480 }
7481
7482 MockURLRequestInterceptor* interceptor() const {
7483 return interceptor_;
7484 }
7485
7486 private:
7487 MockURLRequestInterceptor* interceptor_;
7488};
7489
7490TEST_F(URLRequestInterceptorTestHTTP,
7491 NetworkDelegateNotificationOnRedirectIntercept) {
7492 interceptor()->set_intercept_redirect(true);
7493 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7494 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7495
tommycli59a63432015-11-06 00:10:557496 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507497
7498 TestDelegate d;
7499 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557500 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507501 req->Start();
7502 base::RunLoop().Run();
7503
7504 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7505 // Check we got one good response
7506 EXPECT_TRUE(req->status().is_success());
7507 if (req->status().is_success())
7508 EXPECT_EQ(200, req->response_headers()->response_code());
7509
7510 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7511 EXPECT_EQ(1, d.response_started_count());
7512 EXPECT_EQ(0, d.received_redirect_count());
7513
7514 EXPECT_EQ(1, default_network_delegate()->created_requests());
7515 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7516 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7517}
7518
7519TEST_F(URLRequestInterceptorTestHTTP,
7520 NetworkDelegateNotificationOnErrorIntercept) {
7521 // Intercept that error and respond with an OK response.
7522 interceptor()->set_intercept_final_response(true);
7523 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7524 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7525 default_network_delegate()->set_can_be_intercepted_on_error(true);
7526
tommycli59a63432015-11-06 00:10:557527 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507528
7529 TestDelegate d;
7530 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557531 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:367532 &d));
bengr1bf8e942014-11-07 01:36:507533 req->set_method("GET");
7534 req->Start();
7535 base::RunLoop().Run();
7536
7537 EXPECT_TRUE(interceptor()->did_intercept_final());
7538
7539 // Check we received one good response.
7540 EXPECT_TRUE(req->status().is_success());
7541 if (req->status().is_success())
7542 EXPECT_EQ(200, req->response_headers()->response_code());
7543 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7544 EXPECT_EQ(1, d.response_started_count());
7545 EXPECT_EQ(0, d.received_redirect_count());
7546
7547 EXPECT_EQ(1, default_network_delegate()->created_requests());
7548 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7549 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7550}
7551
7552TEST_F(URLRequestInterceptorTestHTTP,
7553 NetworkDelegateNotificationOnResponseIntercept) {
7554 // Intercept that error and respond with an OK response.
7555 interceptor()->set_intercept_final_response(true);
7556
7557 // Intercept with a real URLRequestHttpJob.
7558 interceptor()->set_use_url_request_http_job(true);
7559
tommycli59a63432015-11-06 00:10:557560 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507561
7562 TestDelegate d;
7563 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557564 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507565 req->set_method("GET");
7566 req->Start();
7567 base::RunLoop().Run();
7568
7569 EXPECT_TRUE(interceptor()->did_intercept_final());
7570
7571 // Check we received one good response.
7572 EXPECT_TRUE(req->status().is_success());
7573 if (req->status().is_success())
7574 EXPECT_EQ(200, req->response_headers()->response_code());
7575 EXPECT_EQ("hello", d.data_received());
7576 EXPECT_EQ(1, d.response_started_count());
7577 EXPECT_EQ(0, d.received_redirect_count());
7578
7579 EXPECT_EQ(1, default_network_delegate()->created_requests());
7580 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7581 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7582}
7583
mkwst0c5eab872014-11-21 14:18:547584class URLRequestTestReferrerPolicy : public URLRequestTest {
7585 public:
7586 URLRequestTestReferrerPolicy() {}
7587
tommycli59a63432015-11-06 00:10:557588 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
7589 origin_server_.reset(new EmbeddedTestServer(type));
7590 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
7591 origin_server_->AddDefaultHandlers(
7592 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7593 } else {
7594 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7595 }
mkwst0c5eab872014-11-21 14:18:547596 ASSERT_TRUE(origin_server_->Start());
7597 }
7598
tommycli59a63432015-11-06 00:10:557599 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
7600 net::EmbeddedTestServer::Type dest_type) {
7601 origin_server_.reset(new EmbeddedTestServer(origin_type));
7602 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7603 origin_server_->AddDefaultHandlers(
7604 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7605 } else {
7606 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7607 }
mkwst0c5eab872014-11-21 14:18:547608 ASSERT_TRUE(origin_server_->Start());
7609
tommycli59a63432015-11-06 00:10:557610 destination_server_.reset(new EmbeddedTestServer(dest_type));
7611 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7612 destination_server_->AddDefaultHandlers(
7613 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7614 } else {
7615 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7616 }
mkwst0c5eab872014-11-21 14:18:547617 ASSERT_TRUE(destination_server_->Start());
7618 }
7619
7620 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7621 const GURL& referrer,
7622 const GURL& expected) {
7623 // Create and execute the request: we'll only have a |destination_server_|
7624 // if the origins are meant to be distinct. Otherwise, we'll use the
7625 // |origin_server_| for both endpoints.
7626 GURL destination_url =
tommycli59a63432015-11-06 00:10:557627 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
7628 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:547629 GURL origin_url =
tommycli59a63432015-11-06 00:10:557630 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:547631
7632 TestDelegate d;
7633 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367634 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547635 req->set_referrer_policy(policy);
7636 req->SetReferrer(referrer.spec());
7637 req->Start();
7638 base::RunLoop().Run();
7639
7640 EXPECT_EQ(1, d.response_started_count());
7641 EXPECT_EQ(1, d.received_redirect_count());
7642 EXPECT_EQ(destination_url, req->url());
7643 EXPECT_TRUE(req->status().is_success());
7644 EXPECT_EQ(200, req->response_headers()->response_code());
7645
7646 EXPECT_EQ(expected.spec(), req->referrer());
7647 if (expected.is_empty())
7648 EXPECT_EQ("None", d.data_received());
7649 else
7650 EXPECT_EQ(expected.spec(), d.data_received());
7651 }
7652
tommycli59a63432015-11-06 00:10:557653 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:547654
7655 private:
tommycli59a63432015-11-06 00:10:557656 scoped_ptr<EmbeddedTestServer> origin_server_;
7657 scoped_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:547658};
7659
7660TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:557661 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547662
7663 VerifyReferrerAfterRedirect(
7664 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557665 origin_server()->GetURL("/path/to/file.html"),
7666 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547667
7668 VerifyReferrerAfterRedirect(
7669 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557670 origin_server()->GetURL("/path/to/file.html"),
7671 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547672
7673 VerifyReferrerAfterRedirect(
7674 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557675 origin_server()->GetURL("/path/to/file.html"),
7676 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547677
7678 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557679 origin_server()->GetURL("/path/to/file.html"),
7680 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547681}
7682
tommycli59a63432015-11-06 00:10:557683TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
7684 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
7685 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547686
7687 VerifyReferrerAfterRedirect(
7688 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557689 origin_server()->GetURL("/path/to/file.html"),
7690 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547691
7692 VerifyReferrerAfterRedirect(
7693 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557694 origin_server()->GetURL("/path/to/file.html"),
7695 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547696
7697 VerifyReferrerAfterRedirect(
7698 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557699 origin_server()->GetURL("/path/to/file.html"),
7700 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547701
7702 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557703 origin_server()->GetURL("/path/to/file.html"),
7704 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547705}
7706
7707TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:557708 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547709
7710 VerifyReferrerAfterRedirect(
7711 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557712 origin_server()->GetURL("/path/to/file.html"),
7713 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547714
7715 VerifyReferrerAfterRedirect(
7716 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557717 origin_server()->GetURL("/path/to/file.html"),
7718 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547719
7720 VerifyReferrerAfterRedirect(
7721 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557722 origin_server()->GetURL("/path/to/file.html"),
7723 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547724
7725 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557726 origin_server()->GetURL("/path/to/file.html"),
7727 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547728}
7729
tommycli59a63432015-11-06 00:10:557730TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7731 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
7732 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547733
7734 VerifyReferrerAfterRedirect(
7735 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557736 origin_server()->GetURL("/path/to/file.html"),
7737 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547738
7739 VerifyReferrerAfterRedirect(
7740 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557741 origin_server()->GetURL("/path/to/file.html"),
7742 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547743
7744 VerifyReferrerAfterRedirect(
7745 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557746 origin_server()->GetURL("/path/to/file.html"),
7747 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547748
7749 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557750 origin_server()->GetURL("/path/to/file.html"),
7751 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547752}
7753
tommycli59a63432015-11-06 00:10:557754TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7755 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
7756 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547757
7758 VerifyReferrerAfterRedirect(
7759 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557760 origin_server()->GetURL("/path/to/file.html"),
7761 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547762
7763 VerifyReferrerAfterRedirect(
7764 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557765 origin_server()->GetURL("/path/to/file.html"),
7766 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547767
7768 VerifyReferrerAfterRedirect(
7769 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557770 origin_server()->GetURL("/path/to/file.html"),
7771 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547772
7773 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557774 origin_server()->GetURL("/path/to/file.html"),
7775 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547776}
7777
tommycli59a63432015-11-06 00:10:557778TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7779 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
7780 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"), GURL());
mkwst0c5eab872014-11-21 14:18:547785
7786 VerifyReferrerAfterRedirect(
7787 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557788 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:547789
7790 VerifyReferrerAfterRedirect(
7791 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557792 origin_server()->GetURL("/path/to/file.html"),
7793 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547794
7795 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557796 origin_server()->GetURL("/path/to/file.html"),
7797 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547798}
7799
[email protected]73e0bba2009-02-19 22:57:097800class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507801 public:
[email protected]ef2bf422012-05-11 03:27:097802 HTTPSRequestTest() : default_context_(true) {
7803 default_context_.set_network_delegate(&default_network_delegate_);
7804 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507805 }
dcheng67be2b1f2014-10-27 21:47:297806 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507807
7808 protected:
[email protected]ceefd7fd2012-11-29 00:36:247809 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097810 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467811};
7812
[email protected]c044616e2013-02-20 02:01:267813TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:557814 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7815 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:227816 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117817 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467818
[email protected]ea224582008-12-07 20:25:467819 TestDelegate d;
7820 {
[email protected]f7022f32014-08-21 16:32:197821 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557822 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197823 r->Start();
7824 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467825
[email protected]255620da2013-08-19 13:14:297826 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467827
7828 EXPECT_EQ(1, d.response_started_count());
7829 EXPECT_FALSE(d.received_data_before_response());
7830 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197831 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197832 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197833 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197834 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197835 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467836 }
[email protected]ea224582008-12-07 20:25:467837}
7838
[email protected]5774ada2010-07-15 06:30:547839TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:557840 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7841 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
7842 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:227843 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117844 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337845
7846 bool err_allowed = true;
7847 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7848 TestDelegate d;
7849 {
7850 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197851 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557852 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337853
[email protected]f7022f32014-08-21 16:32:197854 r->Start();
7855 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337856
[email protected]255620da2013-08-19 13:14:297857 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337858
7859 EXPECT_EQ(1, d.response_started_count());
7860 EXPECT_FALSE(d.received_data_before_response());
7861 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177862 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337863 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197864 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177865 } else {
[email protected]bacff652009-03-31 17:50:337866 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177867 }
[email protected]bacff652009-03-31 17:50:337868 }
7869 }
7870}
7871
[email protected]5774ada2010-07-15 06:30:547872TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:557873 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7874 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
7875 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:227876 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117877 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337878
7879 // Iterate from false to true, just so that we do the opposite of the
7880 // previous test in order to increase test coverage.
7881 bool err_allowed = false;
7882 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7883 TestDelegate d;
7884 {
7885 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197886 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557887 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337888
[email protected]f7022f32014-08-21 16:32:197889 r->Start();
7890 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337891
[email protected]255620da2013-08-19 13:14:297892 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337893
7894 EXPECT_EQ(1, d.response_started_count());
7895 EXPECT_FALSE(d.received_data_before_response());
7896 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177897 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337898 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197899 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177900 } else {
[email protected]bacff652009-03-31 17:50:337901 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177902 }
[email protected]bacff652009-03-31 17:50:337903 }
7904 }
7905}
[email protected]73e0bba2009-02-19 22:57:097906
tommycli59a63432015-11-06 00:10:557907// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
7908// security state. (see http://crbug.com/550977).
7909#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:447910// This tests that a load of www.google.com with a certificate error sets
7911// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7912// the interstitial to be fatal.
7913TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
tommycli59a63432015-11-06 00:10:557914 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7915 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
7916 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:447917 ASSERT_TRUE(test_server.Start());
7918
7919 // We require that the URL be www.google.com in order to pick up the
7920 // preloaded HSTS entries in the TransportSecurityState. This means that we
7921 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247922 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447923
7924 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247925 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447926 TestURLRequestContext context(true);
7927 context.set_network_delegate(&network_delegate);
7928 context.set_host_resolver(&host_resolver);
7929 TransportSecurityState transport_security_state;
7930 context.set_transport_security_state(&transport_security_state);
7931 context.Init();
7932
7933 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197934 scoped_ptr<URLRequest> r(context.CreateRequest(
7935 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367936 test_server.host_port_pair().port())),
7937 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447938
[email protected]f7022f32014-08-21 16:32:197939 r->Start();
7940 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447941
[email protected]255620da2013-08-19 13:14:297942 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447943
7944 EXPECT_EQ(1, d.response_started_count());
7945 EXPECT_FALSE(d.received_data_before_response());
7946 EXPECT_TRUE(d.have_certificate_errors());
7947 EXPECT_TRUE(d.certificate_errors_are_fatal());
7948}
7949
7950// This tests that cached HTTPS page loads do not cause any updates to the
7951// TransportSecurityState.
7952TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7953 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7954 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:557955 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7956 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
7957 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:447958 ASSERT_TRUE(test_server.Start());
7959
[email protected]9e6968d2014-05-07 21:46:267960 // We require that the URL be www.google.com in order to pick up the static
7961 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7962 // that we have to use a MockHostResolver in order to direct www.google.com to
7963 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447964
7965 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247966 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447967 TestURLRequestContext context(true);
7968 context.set_network_delegate(&network_delegate);
7969 context.set_host_resolver(&host_resolver);
7970 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267971
martijnc0d6b622015-06-30 19:14:407972 TransportSecurityState::STSState static_sts_state;
7973 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:267974 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:407975 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:447976 context.set_transport_security_state(&transport_security_state);
7977 context.Init();
7978
martijnc0d6b622015-06-30 19:14:407979 TransportSecurityState::STSState dynamic_sts_state;
7980 TransportSecurityState::PKPState dynamic_pkp_state;
7981 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
7982 &dynamic_sts_state));
7983 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
7984 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:267985
[email protected]316c1e5e2012-09-12 15:17:447986 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197987 scoped_ptr<URLRequest> r(context.CreateRequest(
7988 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367989 test_server.host_port_pair().port())),
7990 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447991
[email protected]f7022f32014-08-21 16:32:197992 r->Start();
7993 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447994
[email protected]255620da2013-08-19 13:14:297995 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447996
7997 EXPECT_EQ(1, d.response_started_count());
7998 EXPECT_FALSE(d.received_data_before_response());
7999 EXPECT_TRUE(d.have_certificate_errors());
8000 EXPECT_TRUE(d.certificate_errors_are_fatal());
8001
[email protected]9e6968d2014-05-07 21:46:268002 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408003 TransportSecurityState::STSState new_static_sts_state;
8004 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268005 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408006 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8007 TransportSecurityState::STSState new_dynamic_sts_state;
8008 TransportSecurityState::PKPState new_dynamic_pkp_state;
8009 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8010 "www.google.com", &new_dynamic_sts_state));
8011 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8012 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268013
martijnc0d6b622015-06-30 19:14:408014 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8015 EXPECT_EQ(new_static_sts_state.include_subdomains,
8016 static_sts_state.include_subdomains);
8017 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8018 static_pkp_state.include_subdomains);
8019 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.spki_hashes,
8020 static_pkp_state.spki_hashes));
8021 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.bad_spki_hashes,
8022 static_pkp_state.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:448023}
8024
[email protected]8ccc69f2012-11-28 19:52:148025// Make sure HSTS preserves a POST request's method and body.
8026TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8027 static const char kData[] = "hello world";
8028
tommycli59a63432015-11-06 00:10:558029 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8030 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228031 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148032 ASSERT_TRUE(test_server.Start());
8033
8034
8035 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8036 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:558037 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:228038 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148039 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148040
8041 // Force https for www.somewhere.com.
8042 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208043 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8044 bool include_subdomains = false;
8045 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8046 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148047
8048 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8049
8050 TestURLRequestContext context(true);
8051 context.set_host_resolver(&host_resolver);
8052 context.set_transport_security_state(&transport_security_state);
8053 context.set_network_delegate(&network_delegate);
8054 context.Init();
8055
8056 TestDelegate d;
8057 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8058 // cause a certificate error. Ignore the error.
8059 d.set_allow_certificate_errors(true);
8060
[email protected]f7022f32014-08-21 16:32:198061 scoped_ptr<URLRequest> req(context.CreateRequest(
8062 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368063 test_server.host_port_pair().port())),
8064 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198065 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078066 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148067
[email protected]f7022f32014-08-21 16:32:198068 req->Start();
[email protected]255620da2013-08-19 13:14:298069 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148070
[email protected]f7022f32014-08-21 16:32:198071 EXPECT_EQ("https", req->url().scheme());
8072 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148073 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408074
8075 LoadTimingInfo load_timing_info;
8076 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8077 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8078 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148079}
8080
rob4e0be1f2014-09-11 23:40:228081// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8082TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8083 static const char kOriginHeaderValue[] = "http://www.example.com";
8084
tommycli59a63432015-11-06 00:10:558085 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8086 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:228087 ASSERT_TRUE(test_server.Start());
8088
8089 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8090 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:558091 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
8092 // default.
rob4e0be1f2014-09-11 23:40:228093 MockHostResolver host_resolver;
8094
8095 TransportSecurityState transport_security_state;
8096 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8097 bool include_subdomains = false;
8098 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8099
8100 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8101
8102 MockCertVerifier cert_verifier;
8103 cert_verifier.set_default_result(OK);
8104
8105 TestURLRequestContext context(true);
8106 context.set_host_resolver(&host_resolver);
8107 context.set_transport_security_state(&transport_security_state);
8108 context.set_network_delegate(&network_delegate);
8109 context.set_cert_verifier(&cert_verifier);
8110 context.Init();
8111
8112 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8113 test_server.host_port_pair().port()));
8114 url::Replacements<char> replacements;
8115 const char kNewScheme[] = "https";
8116 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8117 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8118
8119 TestDelegate d;
8120 // Quit on redirect to allow response header inspection upon redirect.
8121 d.set_quit_on_redirect(true);
8122
davidben151423e2015-03-23 18:48:368123 scoped_ptr<URLRequest> req(
8124 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228125 // Set Origin header to simulate a cross-origin request.
8126 HttpRequestHeaders request_headers;
8127 request_headers.SetHeader("Origin", kOriginHeaderValue);
8128 req->SetExtraRequestHeaders(request_headers);
8129
8130 req->Start();
8131 base::RunLoop().Run();
8132
8133 EXPECT_EQ(1, d.received_redirect_count());
8134
8135 const HttpResponseHeaders* headers = req->response_headers();
8136 std::string redirect_location;
8137 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8138 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8139
8140 std::string received_cors_header;
8141 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8142 &received_cors_header));
8143 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8144}
8145
Adam Ricecb76ac62015-02-20 05:33:258146// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
8147// are performed in net/websockets/websocket_end_to_end_test.cc.
8148TEST(WebSocketURLRequestTest, HSTSApplied) {
8149 TestNetworkDelegate network_delegate;
8150 TransportSecurityState transport_security_state;
8151 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8152 bool include_subdomains = false;
8153 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8154 TestURLRequestContext context(true);
8155 context.set_transport_security_state(&transport_security_state);
8156 context.set_network_delegate(&network_delegate);
8157 context.Init();
8158 GURL ws_url("ws://example.net/echo");
8159 TestDelegate delegate;
8160 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:368161 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:258162 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
8163 EXPECT_TRUE(ws_url.SchemeIs("wss"));
8164}
8165
[email protected]316c1e5e2012-09-12 15:17:448166namespace {
8167
8168class SSLClientAuthTestDelegate : public TestDelegate {
8169 public:
8170 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8171 }
dchengb03027d2014-10-21 12:00:208172 void OnCertificateRequested(URLRequest* request,
8173 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448174 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178175 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448176 }
8177 int on_certificate_requested_count() {
8178 return on_certificate_requested_count_;
8179 }
8180 private:
8181 int on_certificate_requested_count_;
8182};
8183
8184} // namespace
8185
8186// TODO(davidben): Test the rest of the code. Specifically,
8187// - Filtering which certificates to select.
8188// - Sending a certificate back.
8189// - Getting a certificate request in an SSL renegotiation sending the
8190// HTTP request.
8191TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:558192 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8193 net::SSLServerConfig ssl_config;
8194 ssl_config.require_client_cert = true;
8195 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
8196 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228197 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448198 ASSERT_TRUE(test_server.Start());
8199
8200 SSLClientAuthTestDelegate d;
8201 {
[email protected]f7022f32014-08-21 16:32:198202 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558203 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448204
[email protected]f7022f32014-08-21 16:32:198205 r->Start();
8206 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448207
[email protected]255620da2013-08-19 13:14:298208 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448209
8210 EXPECT_EQ(1, d.on_certificate_requested_count());
8211 EXPECT_FALSE(d.received_data_before_response());
8212 EXPECT_EQ(0, d.bytes_received());
8213
8214 // Send no certificate.
8215 // TODO(davidben): Get temporary client cert import (with keys) working on
8216 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:548217 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:448218
[email protected]255620da2013-08-19 13:14:298219 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448220
8221 EXPECT_EQ(1, d.response_started_count());
8222 EXPECT_FALSE(d.received_data_before_response());
8223 EXPECT_NE(0, d.bytes_received());
8224 }
8225}
8226
8227TEST_F(HTTPSRequestTest, ResumeTest) {
8228 // Test that we attempt a session resume when making two connections to the
8229 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228230 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448231 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228232 SpawnedTestServer test_server(
8233 SpawnedTestServer::TYPE_HTTPS,
8234 ssl_options,
8235 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448236 ASSERT_TRUE(test_server.Start());
8237
8238 SSLClientSocket::ClearSessionCache();
8239
8240 {
8241 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198242 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368243 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448244
[email protected]f7022f32014-08-21 16:32:198245 r->Start();
8246 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448247
[email protected]255620da2013-08-19 13:14:298248 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448249
8250 EXPECT_EQ(1, d.response_started_count());
8251 }
8252
8253 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8254 CloseAllConnections();
8255
8256 {
8257 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198258 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368259 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448260
[email protected]f7022f32014-08-21 16:32:198261 r->Start();
8262 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448263
[email protected]255620da2013-08-19 13:14:298264 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448265
8266 // The response will look like;
8267 // insert abc
8268 // lookup abc
8269 // insert xyz
8270 //
8271 // With a newline at the end which makes the split think that there are
8272 // four lines.
8273
8274 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298275 std::vector<std::string> lines = base::SplitString(
8276 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448277 ASSERT_EQ(4u, lines.size()) << d.data_received();
8278
8279 std::string session_id;
8280
8281 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298282 std::vector<std::string> parts = base::SplitString(
8283 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448284 ASSERT_EQ(2u, parts.size());
8285 if (i == 0) {
8286 EXPECT_EQ("insert", parts[0]);
8287 session_id = parts[1];
8288 } else {
8289 EXPECT_EQ("lookup", parts[0]);
8290 EXPECT_EQ(session_id, parts[1]);
8291 }
8292 }
8293 }
8294}
8295
Adam Langley32352ad2014-10-14 22:31:008296// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8297// the result of fetching "ssl-session-cache" from the test server, indicates
8298// that exactly two different sessions were inserted, with no lookups etc.
8299static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298300 std::vector<std::string> lines = base::SplitString(
8301 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008302 ASSERT_EQ(3u, lines.size()) << session_info;
8303
8304 std::string session_id;
8305 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298306 std::vector<std::string> parts = base::SplitString(
8307 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008308 ASSERT_EQ(2u, parts.size());
8309 EXPECT_EQ("insert", parts[0]);
8310 if (i == 0) {
8311 session_id = parts[1];
8312 } else {
8313 EXPECT_NE(session_id, parts[1]);
8314 }
8315 }
8316}
8317
[email protected]316c1e5e2012-09-12 15:17:448318TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8319 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8320 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228321 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448322 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228323 SpawnedTestServer test_server(
8324 SpawnedTestServer::TYPE_HTTPS,
8325 ssl_options,
8326 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448327 ASSERT_TRUE(test_server.Start());
8328
8329 SSLClientSocket::ClearSessionCache();
8330
8331 {
8332 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198333 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368334 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448335
[email protected]f7022f32014-08-21 16:32:198336 r->Start();
8337 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448338
[email protected]255620da2013-08-19 13:14:298339 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448340
8341 EXPECT_EQ(1, d.response_started_count());
8342 }
8343
8344 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8345 HttpNetworkSession::Params params;
8346 params.host_resolver = default_context_.host_resolver();
8347 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118348 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:448349 params.proxy_service = default_context_.proxy_service();
8350 params.ssl_config_service = default_context_.ssl_config_service();
8351 params.http_auth_handler_factory =
8352 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:418353 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:448354 params.http_server_properties = default_context_.http_server_properties();
8355 params.ssl_session_cache_shard = "alternate";
8356
mmenkee65e7af2015-10-13 17:16:428357 HttpNetworkSession network_session(params);
[email protected]cba24642014-08-15 20:49:598358 scoped_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428359 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448360
8361 default_context_.set_http_transaction_factory(cache.get());
8362
8363 {
8364 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198365 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368366 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448367
[email protected]f7022f32014-08-21 16:32:198368 r->Start();
8369 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448370
[email protected]255620da2013-08-19 13:14:298371 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448372
8373 // The response will look like;
8374 // insert abc
8375 // insert xyz
8376 //
8377 // With a newline at the end which makes the split think that there are
8378 // three lines.
8379
8380 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008381 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448382 }
8383}
8384
davidben8ecc3072014-09-03 23:19:098385#if defined(OS_WIN)
8386
8387namespace {
8388
8389bool IsECDSACipherSuite(uint16_t cipher_suite) {
8390 const char* key_exchange;
8391 const char* cipher;
8392 const char* mac;
8393 bool is_aead;
8394 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
8395 return std::string(key_exchange).find("ECDSA") != std::string::npos;
8396}
8397
8398} // namespace
8399
8400// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
8401// verified.
davidben9399c952014-10-07 04:09:118402TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:098403 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
8404 LOG(INFO) << "Skipping test on this version.";
8405 return;
8406 }
8407
tommycli59a63432015-11-06 00:10:558408 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8409 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
davidben8ecc3072014-09-03 23:19:098410 ASSERT_TRUE(test_server.Start());
8411
8412 TestDelegate d;
8413 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558414 test_server.GetURL("/client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:098415 r->Start();
8416 EXPECT_TRUE(r->is_pending());
8417
8418 base::RunLoop().Run();
8419
8420 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298421 std::vector<std::string> lines = base::SplitString(
8422 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
davidben8ecc3072014-09-03 23:19:098423
8424 for (size_t i = 0; i < lines.size(); i++) {
8425 int cipher_suite;
8426 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
8427 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
8428 << "ClientHello advertised " << cipher_suite;
8429 }
8430}
8431
8432#endif // OS_WIN
8433
Adam Langley32352ad2014-10-14 22:31:008434class TestSSLConfigService : public SSLConfigService {
8435 public:
8436 TestSSLConfigService(bool ev_enabled,
8437 bool online_rev_checking,
8438 bool rev_checking_required_local_anchors)
8439 : ev_enabled_(ev_enabled),
8440 online_rev_checking_(online_rev_checking),
8441 rev_checking_required_local_anchors_(
8442 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:028443 min_version_(kDefaultSSLVersionMin),
8444 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
8445
8446 void set_min_version(uint16 version) {
8447 min_version_ = version;
8448 }
Adam Langley32352ad2014-10-14 22:31:008449
8450 void set_fallback_min_version(uint16 version) {
8451 fallback_min_version_ = version;
8452 }
8453
8454 // SSLConfigService:
dchengb03027d2014-10-21 12:00:208455 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:008456 *config = SSLConfig();
8457 config->rev_checking_enabled = online_rev_checking_;
8458 config->verify_ev_cert = ev_enabled_;
8459 config->rev_checking_required_local_anchors =
8460 rev_checking_required_local_anchors_;
8461 if (fallback_min_version_) {
8462 config->version_fallback_min = fallback_min_version_;
8463 }
Adam Langleyac6f24b42014-10-31 20:24:028464 if (min_version_) {
8465 config->version_min = min_version_;
8466 }
Adam Langley32352ad2014-10-14 22:31:008467 }
8468
8469 protected:
dchengb03027d2014-10-21 12:00:208470 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:008471
8472 private:
8473 const bool ev_enabled_;
8474 const bool online_rev_checking_;
8475 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:028476 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:008477 uint16 fallback_min_version_;
8478};
8479
8480class FallbackTestURLRequestContext : public TestURLRequestContext {
8481 public:
8482 explicit FallbackTestURLRequestContext(bool delay_initialization)
8483 : TestURLRequestContext(delay_initialization) {}
8484
8485 void set_fallback_min_version(uint16 version) {
8486 TestSSLConfigService *ssl_config_service =
8487 new TestSSLConfigService(true /* check for EV */,
8488 false /* online revocation checking */,
8489 false /* require rev. checking for local
8490 anchors */);
8491 ssl_config_service->set_fallback_min_version(version);
8492 set_ssl_config_service(ssl_config_service);
8493 }
8494};
8495
[email protected]48d2b7c52014-06-27 01:16:558496class HTTPSFallbackTest : public testing::Test {
8497 public:
Adam Langley32352ad2014-10-14 22:31:008498 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298499 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558500
8501 protected:
8502 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8503 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008504 context_.Init();
8505 delegate_.set_allow_certificate_errors(true);
8506
[email protected]48d2b7c52014-06-27 01:16:558507 SpawnedTestServer test_server(
8508 SpawnedTestServer::TYPE_HTTPS,
8509 ssl_options,
8510 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8511 ASSERT_TRUE(test_server.Start());
8512
tommycli59a63432015-11-06 00:10:558513 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
8514 &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558515 request_->Start();
8516
8517 base::RunLoop().Run();
8518 }
8519
Adam Langley32352ad2014-10-14 22:31:008520 void set_fallback_min_version(uint16 version) {
8521 context_.set_fallback_min_version(version);
8522 }
8523
[email protected]48d2b7c52014-06-27 01:16:558524 void ExpectConnection(int version) {
8525 EXPECT_EQ(1, delegate_.response_started_count());
8526 EXPECT_NE(0, delegate_.bytes_received());
8527 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8528 request_->ssl_info().connection_status));
8529 EXPECT_TRUE(request_->ssl_info().connection_status &
8530 SSL_CONNECTION_VERSION_FALLBACK);
8531 }
8532
8533 void ExpectFailure(int error) {
8534 EXPECT_EQ(1, delegate_.response_started_count());
8535 EXPECT_FALSE(request_->status().is_success());
8536 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8537 EXPECT_EQ(error, request_->status().error());
8538 }
8539
8540 private:
8541 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008542 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558543 scoped_ptr<URLRequest> request_;
8544};
8545
davidbenb127ca82015-06-15 19:05:428546// Tests the TLS 1.0 fallback doesn't happen.
8547TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558548 SpawnedTestServer::SSLOptions ssl_options(
8549 SpawnedTestServer::SSLOptions::CERT_OK);
8550 ssl_options.tls_intolerant =
8551 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8552
8553 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428554 ExpectFailure(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION);
8555}
8556
8557// Tests the TLS 1.1 fallback.
8558TEST_F(HTTPSFallbackTest, TLSv1_1Fallback) {
davidbenb127ca82015-06-15 19:05:428559 SpawnedTestServer::SSLOptions ssl_options(
8560 SpawnedTestServer::SSLOptions::CERT_OK);
8561 ssl_options.tls_intolerant =
8562 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8563
8564 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8565 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
8566}
8567
8568// Tests that the TLS 1.1 fallback triggers on closed connections.
8569TEST_F(HTTPSFallbackTest, TLSv1_1FallbackClosed) {
davidbenb127ca82015-06-15 19:05:428570 SpawnedTestServer::SSLOptions ssl_options(
8571 SpawnedTestServer::SSLOptions::CERT_OK);
8572 ssl_options.tls_intolerant =
8573 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8574 ssl_options.tls_intolerance_type =
8575 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8576
8577 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8578 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558579}
8580
8581// This test is disabled on Android because the remote test server doesn't cause
8582// a TCP reset.
8583#if !defined(OS_ANDROID)
davidbenb127ca82015-06-15 19:05:428584// Tests fallback to TLS 1.1 on connection reset.
8585TEST_F(HTTPSFallbackTest, TLSv1_1FallbackReset) {
[email protected]48d2b7c52014-06-27 01:16:558586 SpawnedTestServer::SSLOptions ssl_options(
8587 SpawnedTestServer::SSLOptions::CERT_OK);
8588 ssl_options.tls_intolerant =
davidbenb127ca82015-06-15 19:05:428589 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
[email protected]48d2b7c52014-06-27 01:16:558590 ssl_options.tls_intolerance_type =
8591 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8592
8593 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428594 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558595}
8596#endif // !OS_ANDROID
8597
[email protected]12833302014-07-02 01:57:318598// Tests that we don't fallback on handshake failure with servers that implement
8599// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558600TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558601 SpawnedTestServer::SSLOptions ssl_options(
8602 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438603 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558604 // a version fallback.
8605 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438606 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558607 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8608 // connections are rejected.
8609 ssl_options.fallback_scsv_enabled = true;
8610
8611 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8612
8613 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8614 // intolerance. If the fallback SCSV is processed when the original error
8615 // that caused the fallback should be returned, which should be
8616 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8617 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8618}
8619
[email protected]12833302014-07-02 01:57:318620// Tests that we don't fallback on connection closed with servers that implement
8621// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318622TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318623 SpawnedTestServer::SSLOptions ssl_options(
8624 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438625 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318626 // a version fallback.
8627 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438628 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318629 ssl_options.tls_intolerance_type =
8630 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8631 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8632 // connections are rejected.
8633 ssl_options.fallback_scsv_enabled = true;
8634
8635 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8636
8637 // The original error should be replayed on rejected fallback.
8638 ExpectFailure(ERR_CONNECTION_CLOSED);
8639}
8640
davidbenb937d6c2015-05-14 04:53:428641// Test that fallback probe connections don't cause sessions to be cached.
8642TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008643 SpawnedTestServer::SSLOptions ssl_options(
8644 SpawnedTestServer::SSLOptions::CERT_OK);
8645 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428646 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008647 ssl_options.tls_intolerance_type =
8648 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8649 ssl_options.record_resume = true;
8650
8651 SpawnedTestServer test_server(
8652 SpawnedTestServer::TYPE_HTTPS,
8653 ssl_options,
8654 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8655 ASSERT_TRUE(test_server.Start());
8656
8657 SSLClientSocket::ClearSessionCache();
8658
davidbenb937d6c2015-05-14 04:53:428659 // Make a connection that does a probe fallback to TLSv1 but fails because
8660 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008661 // be inserted locally.
8662 {
8663 TestDelegate delegate;
8664 FallbackTestURLRequestContext context(true);
8665
davidbenb937d6c2015-05-14 04:53:428666 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008667 context.Init();
8668 scoped_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558669 test_server.GetURL("/"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008670 request->Start();
8671
8672 base::RunLoop().Run();
8673
8674 EXPECT_EQ(1, delegate.response_started_count());
8675 EXPECT_FALSE(request->status().is_success());
8676 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8677 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8678 request->status().error());
8679 }
8680
davidbenb937d6c2015-05-14 04:53:428681 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008682 {
8683 TestDelegate delegate;
8684 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428685 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008686
8687 context.Init();
davidben151423e2015-03-23 18:48:368688 scoped_ptr<URLRequest> request(context.CreateRequest(
8689 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008690 request->Start();
8691
8692 base::RunLoop().Run();
8693
8694 EXPECT_EQ(1, delegate.response_started_count());
8695 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428696 EXPECT_EQ(
8697 SSL_CONNECTION_VERSION_TLS1,
8698 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008699 EXPECT_TRUE(request->ssl_info().connection_status &
8700 SSL_CONNECTION_VERSION_FALLBACK);
8701
8702 std::vector<std::string> lines;
8703 // If no sessions were cached then the server should have seen two sessions
8704 // inserted with no lookups.
8705 AssertTwoDistinctSessionsInserted(delegate.data_received());
8706 }
8707}
8708
[email protected]a8fed1742013-12-27 02:14:248709class HTTPSSessionTest : public testing::Test {
8710 public:
8711 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598712 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248713
8714 default_context_.set_network_delegate(&default_network_delegate_);
8715 default_context_.set_cert_verifier(&cert_verifier_);
8716 default_context_.Init();
8717 }
dcheng67be2b1f2014-10-27 21:47:298718 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248719
8720 protected:
8721 MockCertVerifier cert_verifier_;
8722 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8723 TestURLRequestContext default_context_;
8724};
8725
8726// Tests that session resumption is not attempted if an invalid certificate
8727// is presented.
8728TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8729 SpawnedTestServer::SSLOptions ssl_options;
8730 ssl_options.record_resume = true;
8731 SpawnedTestServer test_server(
8732 SpawnedTestServer::TYPE_HTTPS,
8733 ssl_options,
8734 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8735 ASSERT_TRUE(test_server.Start());
8736
8737 SSLClientSocket::ClearSessionCache();
8738
8739 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598740 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248741 {
8742 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198743 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368744 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248745
[email protected]f7022f32014-08-21 16:32:198746 r->Start();
8747 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248748
8749 base::RunLoop().Run();
8750
8751 EXPECT_EQ(1, d.response_started_count());
8752 }
8753
8754 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8755 CloseAllConnections();
8756
8757 // Now change the certificate to be acceptable (so that the response is
8758 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598759 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248760 {
8761 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198762 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368763 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248764
[email protected]f7022f32014-08-21 16:32:198765 r->Start();
8766 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248767
8768 base::RunLoop().Run();
8769
8770 // The response will look like;
8771 // insert abc
8772 // insert xyz
8773 //
8774 // With a newline at the end which makes the split think that there are
8775 // three lines.
8776 //
8777 // If a session was presented (eg: a bug), then the response would look
8778 // like;
8779 // insert abc
8780 // lookup abc
8781 // insert xyz
8782
8783 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008784 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248785 }
8786}
8787
[email protected]dffe8242012-03-20 15:14:278788// This the fingerprint of the "Testing CA" certificate used by the testserver.
8789// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268790static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278791 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8792 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8793
[email protected]51523f52013-07-31 21:57:288794// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8795// testserver.
8796static const SHA256HashValue kOCSPTestCertSPKI = { {
8797 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8798 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8799 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8800 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8801} };
8802
[email protected]dffe8242012-03-20 15:14:278803// This is the policy OID contained in the certificates that testserver
8804// generates.
8805static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8806
8807class HTTPSOCSPTest : public HTTPSRequestTest {
8808 public:
8809 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098810 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088811 ev_test_policy_(
8812 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8813 kOCSPTestCertFingerprint,
8814 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028815 }
8816
dcheng67be2b1f2014-10-27 21:47:298817 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098818 SetupContext(&context_);
8819 context_.Init();
[email protected]dffe8242012-03-20 15:14:278820
[email protected]cba24642014-08-15 20:49:598821 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208822 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428823 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508824 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278825
davidben71f35ff2015-04-17 20:54:488826#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098827 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278828 EnsureNSSHttpIOInit();
8829#endif
8830 }
8831
[email protected]ce7d0cbc2013-05-03 18:57:228832 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278833 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538834 // We always overwrite out_cert_status.
8835 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228836 SpawnedTestServer test_server(
8837 SpawnedTestServer::TYPE_HTTPS,
8838 ssl_options,
8839 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278840 ASSERT_TRUE(test_server.Start());
8841
8842 TestDelegate d;
8843 d.set_allow_certificate_errors(true);
tommycli59a63432015-11-06 00:10:558844 scoped_ptr<URLRequest> r(
8845 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198846 r->Start();
[email protected]dffe8242012-03-20 15:14:278847
[email protected]255620da2013-08-19 13:14:298848 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278849
8850 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198851 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278852 }
8853
dcheng67be2b1f2014-10-27 21:47:298854 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488855#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278856 ShutdownNSSHttpIO();
8857#endif
8858 }
8859
[email protected]a13234c2012-03-20 21:45:028860 protected:
8861 // SetupContext configures the URLRequestContext that will be used for making
8862 // connetions to testserver. This can be overridden in test subclasses for
8863 // different behaviour.
8864 virtual void SetupContext(URLRequestContext* context) {
8865 context->set_ssl_config_service(
8866 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208867 true /* online revocation checking */,
8868 false /* require rev. checking for local
8869 anchors */));
[email protected]a13234c2012-03-20 21:45:028870 }
8871
[email protected]dffe8242012-03-20 15:14:278872 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098873 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088874 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278875};
8876
[email protected]a13234c2012-03-20 21:45:028877static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018878#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028879 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8880 // have that ability on other platforms.
8881 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8882#else
8883 return 0;
8884#endif
8885}
8886
[email protected]3a86a712013-07-30 07:16:208887// SystemSupportsHardFailRevocationChecking returns true iff the current
8888// operating system supports revocation checking and can distinguish between
8889// situations where a given certificate lacks any revocation information (eg:
8890// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8891// revocation information cannot be obtained (eg: the CRL was unreachable).
8892// If it does not, then tests which rely on 'hard fail' behaviour should be
8893// skipped.
8894static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:488895#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:208896 return true;
8897#else
8898 return false;
8899#endif
8900}
8901
[email protected]a13234c2012-03-20 21:45:028902// SystemUsesChromiumEVMetadata returns true iff the current operating system
8903// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8904// several tests are effected because our testing EV certificate won't be
8905// recognised as EV.
8906static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328907#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578908 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8909 return false;
[email protected]e1b2d732014-03-28 16:20:328910#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8911 // On OS X and Android, we use the system to tell us whether a certificate is
8912 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018913 return false;
8914#else
8915 return true;
8916#endif
8917}
8918
[email protected]b6f2de32012-08-17 04:35:088919static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008920#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578921 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8922 return false;
8923#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028924 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8925#elif defined(OS_ANDROID)
8926 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8927 return false;
8928#else
8929 return true;
8930#endif
8931}
8932
davidbend1fb2f12014-11-08 02:51:008933static bool SystemSupportsOCSPStapling() {
mathpc992e602015-10-21 20:34:038934#if defined(USE_NSS_CERTS) || defined(OS_IOS)
8935 return true;
8936#elif defined(OS_WIN)
8937 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8938#else
8939 return false;
8940#endif
davidbend1fb2f12014-11-08 02:51:008941}
8942
[email protected]dffe8242012-03-20 15:14:278943TEST_F(HTTPSOCSPTest, Valid) {
8944 if (!SystemSupportsOCSP()) {
8945 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8946 return;
8947 }
8948
[email protected]ce7d0cbc2013-05-03 18:57:228949 SpawnedTestServer::SSLOptions ssl_options(
8950 SpawnedTestServer::SSLOptions::CERT_AUTO);
8951 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278952
[email protected]924e9f92012-12-16 22:00:538953 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128954 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278955
8956 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8957
[email protected]a13234c2012-03-20 21:45:028958 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8959 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278960
8961 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8962}
8963
8964TEST_F(HTTPSOCSPTest, Revoked) {
8965 if (!SystemSupportsOCSP()) {
8966 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8967 return;
8968 }
8969
[email protected]ce7d0cbc2013-05-03 18:57:228970 SpawnedTestServer::SSLOptions ssl_options(
8971 SpawnedTestServer::SSLOptions::CERT_AUTO);
8972 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278973
8974 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128975 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278976
[email protected]a592c0432012-12-01 18:10:298977#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278978 // Doesn't pass on OS X yet for reasons that need to be investigated.
8979 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8980#endif
8981 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8982 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8983}
8984
8985TEST_F(HTTPSOCSPTest, Invalid) {
8986 if (!SystemSupportsOCSP()) {
8987 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8988 return;
8989 }
8990
[email protected]ce7d0cbc2013-05-03 18:57:228991 SpawnedTestServer::SSLOptions ssl_options(
8992 SpawnedTestServer::SSLOptions::CERT_AUTO);
8993 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:278994
[email protected]924e9f92012-12-16 22:00:538995 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128996 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278997
[email protected]a13234c2012-03-20 21:45:028998 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278999 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279000
9001 // Without a positive OCSP response, we shouldn't show the EV status.
9002 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9003 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9004}
[email protected]a13234c2012-03-20 21:45:029005
davidbend1fb2f12014-11-08 02:51:009006TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:039007 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009008 LOG(WARNING)
9009 << "Skipping test because system doesn't support OCSP stapling";
9010 return;
9011 }
9012
9013 SpawnedTestServer::SSLOptions ssl_options(
9014 SpawnedTestServer::SSLOptions::CERT_AUTO);
9015 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9016 ssl_options.staple_ocsp_response = true;
9017 ssl_options.ocsp_server_unavailable = true;
9018
9019 CertStatus cert_status;
9020 DoConnection(ssl_options, &cert_status);
9021
9022 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9023
9024 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9025 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9026
9027 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9028}
9029
davidben6c3191b2014-11-21 22:38:049030// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489031#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049032#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9033#else
9034#define MAYBE_RevokedStapled RevokedStapled
9035#endif
9036TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:039037 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009038 LOG(WARNING)
9039 << "Skipping test because system doesn't support OCSP stapling";
9040 return;
9041 }
9042
9043 SpawnedTestServer::SSLOptions ssl_options(
9044 SpawnedTestServer::SSLOptions::CERT_AUTO);
9045 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9046 ssl_options.staple_ocsp_response = true;
9047 ssl_options.ocsp_server_unavailable = true;
9048
9049 CertStatus cert_status;
9050 DoConnection(ssl_options, &cert_status);
9051
9052 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9053 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9054 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9055}
9056
[email protected]3a86a712013-07-30 07:16:209057class HTTPSHardFailTest : public HTTPSOCSPTest {
9058 protected:
dchengb03027d2014-10-21 12:00:209059 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:209060 context->set_ssl_config_service(
9061 new TestSSLConfigService(false /* check for EV */,
9062 false /* online revocation checking */,
9063 true /* require rev. checking for local
9064 anchors */));
9065 }
9066};
9067
[email protected]3a86a712013-07-30 07:16:209068TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
9069 if (!SystemSupportsOCSP()) {
9070 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9071 return;
9072 }
9073
9074 if (!SystemSupportsHardFailRevocationChecking()) {
9075 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
9076 << "revocation checking";
9077 return;
9078 }
9079
9080 SpawnedTestServer::SSLOptions ssl_options(
9081 SpawnedTestServer::SSLOptions::CERT_AUTO);
9082 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9083
9084 CertStatus cert_status;
9085 DoConnection(ssl_options, &cert_status);
9086
9087 EXPECT_EQ(CERT_STATUS_REVOKED,
9088 cert_status & CERT_STATUS_REVOKED);
9089
9090 // Without a positive OCSP response, we shouldn't show the EV status.
9091 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9092}
9093
[email protected]a13234c2012-03-20 21:45:029094class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
9095 protected:
dchengb03027d2014-10-21 12:00:209096 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:029097 context->set_ssl_config_service(
9098 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:209099 false /* online revocation checking */,
9100 false /* require rev. checking for local
9101 anchors */));
[email protected]a13234c2012-03-20 21:45:029102 }
9103};
9104
9105TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
9106 if (!SystemSupportsOCSP()) {
9107 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9108 return;
9109 }
9110
[email protected]ce7d0cbc2013-05-03 18:57:229111 SpawnedTestServer::SSLOptions ssl_options(
9112 SpawnedTestServer::SSLOptions::CERT_AUTO);
9113 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029114 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9115
[email protected]924e9f92012-12-16 22:00:539116 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129117 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029118
9119 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9120 cert_status & CERT_STATUS_ALL_ERRORS);
9121
9122 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089123 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9124 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029125}
9126
[email protected]be0fff62013-08-29 23:37:489127TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
9128 if (!SystemSupportsOCSP()) {
9129 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9130 return;
9131 }
9132
9133 SpawnedTestServer::SSLOptions ssl_options(
9134 SpawnedTestServer::SSLOptions::CERT_AUTO);
9135 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9136 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9137
9138 CertStatus cert_status;
9139 DoConnection(ssl_options, &cert_status);
9140
9141 // Currently only works for Windows. When using NSS or OS X, it's not
9142 // possible to determine whether the check failed because of actual
9143 // revocation or because there was an OCSP failure.
9144#if defined(OS_WIN)
9145 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9146#else
9147 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9148#endif
9149
9150 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9151 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9152 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9153}
9154
[email protected]a13234c2012-03-20 21:45:029155TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
9156 if (!SystemSupportsOCSP()) {
9157 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9158 return;
9159 }
9160
[email protected]ce7d0cbc2013-05-03 18:57:229161 SpawnedTestServer::SSLOptions ssl_options(
9162 SpawnedTestServer::SSLOptions::CERT_AUTO);
9163 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:029164 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9165
9166 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129167 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029168
9169 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9170
9171 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9172 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:089173 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9174 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029175}
9176
9177TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
9178 if (!SystemSupportsOCSP()) {
9179 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9180 return;
9181 }
9182
[email protected]ce7d0cbc2013-05-03 18:57:229183 SpawnedTestServer::SSLOptions ssl_options(
9184 SpawnedTestServer::SSLOptions::CERT_AUTO);
9185 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029186 SSLConfigService::SetCRLSet(
9187 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9188
9189 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129190 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029191
9192 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9193 cert_status & CERT_STATUS_ALL_ERRORS);
9194
9195 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089196 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9197 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029198}
9199
[email protected]51523f52013-07-31 21:57:289200TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9201 if (!SystemSupportsOCSP()) {
9202 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9203 return;
9204 }
9205
9206 SpawnedTestServer::SSLOptions ssl_options(
9207 SpawnedTestServer::SSLOptions::CERT_AUTO);
9208 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9209 SSLConfigService::SetCRLSet(
9210 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9211 false, &kOCSPTestCertSPKI, "")));
9212
9213 CertStatus cert_status;
9214 DoConnection(ssl_options, &cert_status);
9215
9216 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9217 // revocation check for EV.
9218 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9219 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9220 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9221 EXPECT_FALSE(
9222 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9223}
9224
9225TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9226 if (!SystemSupportsOCSP()) {
9227 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9228 return;
9229 }
9230
[email protected]ce7d0cbc2013-05-03 18:57:229231 SpawnedTestServer::SSLOptions ssl_options(
9232 SpawnedTestServer::SSLOptions::CERT_AUTO);
9233 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029234 SSLConfigService::SetCRLSet(
9235 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9236
[email protected]51523f52013-07-31 21:57:289237 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129238 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029239
[email protected]51523f52013-07-31 21:57:289240 // Even with a fresh CRLSet, we should still do online revocation checks when
9241 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9242 // test.
9243 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9244 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029245
[email protected]51523f52013-07-31 21:57:289246 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029247 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289248 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029249}
9250
[email protected]b6f2de32012-08-17 04:35:089251TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9252 // Test that when EV verification is requested, but online revocation
9253 // checking is disabled, and the leaf certificate is not in fact EV, that
9254 // no revocation checking actually happens.
9255 if (!SystemSupportsOCSP()) {
9256 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9257 return;
9258 }
9259
9260 // Unmark the certificate's OID as EV, which should disable revocation
9261 // checking (as per the user preference)
9262 ev_test_policy_.reset();
9263
[email protected]ce7d0cbc2013-05-03 18:57:229264 SpawnedTestServer::SSLOptions ssl_options(
9265 SpawnedTestServer::SSLOptions::CERT_AUTO);
9266 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089267 SSLConfigService::SetCRLSet(
9268 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9269
9270 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129271 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:089272
9273 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9274
9275 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9276 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9277}
9278
[email protected]a13234c2012-03-20 21:45:029279class HTTPSCRLSetTest : public HTTPSOCSPTest {
9280 protected:
dchengb03027d2014-10-21 12:00:209281 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:029282 context->set_ssl_config_service(
9283 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:209284 false /* online revocation checking */,
9285 false /* require rev. checking for local
9286 anchors */));
[email protected]a13234c2012-03-20 21:45:029287 }
9288};
9289
9290TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229291 SpawnedTestServer::SSLOptions ssl_options(
9292 SpawnedTestServer::SSLOptions::CERT_AUTO);
9293 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029294 SSLConfigService::SetCRLSet(
9295 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9296
[email protected]924e9f92012-12-16 22:00:539297 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129298 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029299
9300 // If we're not trying EV verification then, even if the CRLSet has expired,
9301 // we don't fall back to online revocation checks.
9302 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9303 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9304 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9305}
[email protected]51523f52013-07-31 21:57:289306
9307TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309308#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289309 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9310 return;
9311#endif
9312
9313 SpawnedTestServer::SSLOptions ssl_options(
9314 SpawnedTestServer::SSLOptions::CERT_AUTO);
9315 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9316 ssl_options.cert_serial = 10;
9317 SSLConfigService::SetCRLSet(
9318 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9319 false, &kOCSPTestCertSPKI, "\x0a")));
9320
9321 CertStatus cert_status = 0;
9322 DoConnection(ssl_options, &cert_status);
9323
9324 // If the certificate is recorded as revoked in the CRLSet, that should be
9325 // reflected without online revocation checking.
9326 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9327 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9328 EXPECT_FALSE(
9329 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9330}
[email protected]316c1e5e2012-09-12 15:17:449331#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279332
mmenke9f2ec60c2015-06-01 20:59:479333#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9334// These tests aren't passing on Android. Either the RemoteTestServer isn't
9335// starting up successfully, or it can't access the test files.
9336// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319337class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119338 public:
[email protected]d9fca99a2012-02-24 16:16:209339 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:479340 : ftp_transaction_factory_(&host_resolver_),
tommycli59a63432015-11-06 00:10:559341 ftp_test_server_(SpawnedTestServer::TYPE_FTP,
9342 SpawnedTestServer::kLocalhost,
9343 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:479344 // Can't use |default_context_|'s HostResolver to set up the
9345 // FTPTransactionFactory because it hasn't been created yet.
9346 default_context_.set_host_resolver(&host_resolver_);
9347 }
9348
9349 // URLRequestTest interface:
9350 void SetUpFactory() override {
9351 // Add FTP support to the default URLRequestContext.
9352 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:209353 "ftp",
9354 make_scoped_ptr(new FtpProtocolHandler(&ftp_transaction_factory_)));
mmenke9f2ec60c2015-06-01 20:59:479355 }
9356
9357 std::string GetTestFileContents() {
9358 base::FilePath path;
9359 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9360 path = path.Append(kTestFilePath);
9361 path = path.AppendASCII(kFtpTestFile);
9362 std::string contents;
9363 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9364 return contents;
[email protected]95409e12010-08-17 20:07:119365 }
9366
[email protected]b89ca032009-08-31 21:41:319367 protected:
mmenke9f2ec60c2015-06-01 20:59:479368 MockHostResolver host_resolver_;
9369 FtpNetworkLayer ftp_transaction_factory_;
9370
tommycli59a63432015-11-06 00:10:559371 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:319372};
9373
[email protected]d2a133182012-08-05 16:44:089374// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099375TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089376 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089377
9378 TestDelegate d;
9379 {
davidben151423e2015-03-23 18:48:369380 scoped_ptr<URLRequest> r(
9381 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199382 r->Start();
9383 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089384
[email protected]255620da2013-08-19 13:14:299385 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089386
[email protected]f7022f32014-08-21 16:32:199387 EXPECT_FALSE(r->is_pending());
9388 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
9389 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:089390 }
9391}
9392
mmenke9f2ec60c2015-06-01 20:59:479393TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:559394 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119395
[email protected]a25e90e2009-09-09 17:05:379396 TestDelegate d;
9397 {
[email protected]f7022f32014-08-21 16:32:199398 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559399 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199400 r->Start();
9401 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379402
[email protected]255620da2013-08-19 13:14:299403 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379404
[email protected]f7022f32014-08-21 16:32:199405 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379406 EXPECT_EQ(1, d.response_started_count());
9407 EXPECT_FALSE(d.received_data_before_response());
9408 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:559409 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199410 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559411 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199412 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379413 }
9414}
9415
mmenke9f2ec60c2015-06-01 20:59:479416TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:559417 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119418
[email protected]dd265012009-01-08 20:45:279419 TestDelegate d;
9420 {
[email protected]f7022f32014-08-21 16:32:199421 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559422 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199423 r->Start();
9424 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279425
[email protected]255620da2013-08-19 13:14:299426 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279427
[email protected]f7022f32014-08-21 16:32:199428 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279429 EXPECT_EQ(1, d.response_started_count());
9430 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479431 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559432 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199433 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559434 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199435 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279436 }
9437}
9438
mmenke9f2ec60c2015-06-01 20:59:479439TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:559440 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119441
[email protected]dd265012009-01-08 20:45:279442 TestDelegate d;
9443 {
tommycli59a63432015-11-06 00:10:559444 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9445 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9446 "chrome"),
9447 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199448 r->Start();
9449 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279450
[email protected]255620da2013-08-19 13:14:299451 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279452
[email protected]f7022f32014-08-21 16:32:199453 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479454 EXPECT_EQ(1, d.response_started_count());
9455 EXPECT_FALSE(d.received_data_before_response());
9456 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559457 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199458 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559459 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199460 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:259461
9462 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:199463 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:259464 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:279465 }
9466}
9467
mmenke9f2ec60c2015-06-01 20:59:479468TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:559469 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119470
[email protected]dd265012009-01-08 20:45:279471 TestDelegate d;
9472 {
[email protected]f7022f32014-08-21 16:32:199473 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559474 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9475 "wrong_password"),
davidben151423e2015-03-23 18:48:369476 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199477 r->Start();
9478 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279479
[email protected]255620da2013-08-19 13:14:299480 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279481
[email protected]f7022f32014-08-21 16:32:199482 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279483 EXPECT_EQ(1, d.response_started_count());
9484 EXPECT_FALSE(d.received_data_before_response());
9485 EXPECT_EQ(d.bytes_received(), 0);
9486 }
9487}
9488
mmenke9f2ec60c2015-06-01 20:59:479489TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:559490 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119491
[email protected]8b8a197d2009-08-26 15:57:589492 TestDelegate d;
9493 // Set correct login credentials. The delegate will be asked for them when
9494 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589495 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589496 {
[email protected]f7022f32014-08-21 16:32:199497 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559498 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9499 "wrong_password"),
davidben151423e2015-03-23 18:48:369500 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199501 r->Start();
9502 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589503
[email protected]255620da2013-08-19 13:14:299504 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589505
[email protected]f7022f32014-08-21 16:32:199506 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589507 EXPECT_EQ(1, d.response_started_count());
9508 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479509 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589510 }
9511}
9512
mmenke9f2ec60c2015-06-01 20:59:479513TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:559514 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119515
[email protected]dd265012009-01-08 20:45:279516 TestDelegate d;
9517 {
mmenke9f2ec60c2015-06-01 20:59:479518 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559519 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9520 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479521 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199522 r->Start();
9523 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279524
[email protected]255620da2013-08-19 13:14:299525 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279526
[email protected]f7022f32014-08-21 16:32:199527 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279528 EXPECT_EQ(1, d.response_started_count());
9529 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479530 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279531 }
9532}
[email protected]8b8a197d2009-08-26 15:57:589533
mmenke9f2ec60c2015-06-01 20:59:479534TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:559535 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119536
[email protected]8b8a197d2009-08-26 15:57:589537 TestDelegate d;
9538 // Set correct login credentials. The delegate will be asked for them when
9539 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589540 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589541 {
mmenke9f2ec60c2015-06-01 20:59:479542 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559543 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9544 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479545 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199546 r->Start();
9547 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589548
[email protected]255620da2013-08-19 13:14:299549 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589550
[email protected]f7022f32014-08-21 16:32:199551 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589552 EXPECT_EQ(1, d.response_started_count());
9553 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479554 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589555 }
9556}
[email protected]60a3df52009-09-22 16:13:249557
mmenke9f2ec60c2015-06-01 20:59:479558TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:559559 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119560
[email protected]60a3df52009-09-22 16:13:249561 scoped_ptr<TestDelegate> d(new TestDelegate);
9562 {
9563 // Pass correct login identity in the URL.
tommycli59a63432015-11-06 00:10:559564 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9565 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9566 "chrome"),
9567 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199568 r->Start();
9569 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249570
[email protected]255620da2013-08-19 13:14:299571 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249572
[email protected]f7022f32014-08-21 16:32:199573 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249574 EXPECT_EQ(1, d->response_started_count());
9575 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479576 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249577 }
9578
9579 d.reset(new TestDelegate);
9580 {
9581 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199582 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559583 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199584 r->Start();
9585 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249586
[email protected]255620da2013-08-19 13:14:299587 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249588
[email protected]f7022f32014-08-21 16:32:199589 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249590 EXPECT_EQ(1, d->response_started_count());
9591 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479592 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249593 }
9594}
9595
mmenke9f2ec60c2015-06-01 20:59:479596TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:559597 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119598
[email protected]60a3df52009-09-22 16:13:249599 scoped_ptr<TestDelegate> d(new TestDelegate);
9600 // Set correct login credentials. The delegate will be asked for them when
9601 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589602 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249603 {
[email protected]f7022f32014-08-21 16:32:199604 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559605 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9606 "wrong_password"),
davidben151423e2015-03-23 18:48:369607 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199608 r->Start();
9609 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249610
[email protected]255620da2013-08-19 13:14:299611 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249612
[email protected]f7022f32014-08-21 16:32:199613 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249614 EXPECT_EQ(1, d->response_started_count());
9615 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479616 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249617 }
9618
9619 // Use a new delegate without explicit credentials. The cached ones should be
9620 // used.
9621 d.reset(new TestDelegate);
9622 {
9623 // Don't pass wrong credentials in the URL, they would override valid cached
9624 // ones.
[email protected]f7022f32014-08-21 16:32:199625 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559626 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199627 r->Start();
9628 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249629
[email protected]255620da2013-08-19 13:14:299630 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249631
[email protected]f7022f32014-08-21 16:32:199632 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249633 EXPECT_EQ(1, d->response_started_count());
9634 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479635 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249636 }
9637}
[email protected]316c1e5e2012-09-12 15:17:449638#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519639
ttuttlec0c828492015-05-15 01:25:559640TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9641 TestDelegate d;
9642 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9643 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9644 d.set_quit_on_network_start(true);
9645
9646 EXPECT_FALSE(req->response_info().network_accessed);
9647
9648 req->Start();
9649 base::RunLoop().Run();
9650
9651 EXPECT_EQ(1, d.received_before_network_start_count());
9652 EXPECT_EQ(0, d.response_started_count());
9653 EXPECT_FALSE(req->response_info().network_accessed);
9654
9655 req->ResumeNetworkStart();
9656 base::RunLoop().Run();
9657}
9658
9659TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9660 TestDelegate d;
9661 scoped_ptr<URLRequest> req(
9662 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9663
9664 EXPECT_FALSE(req->response_info().network_accessed);
9665
9666 req->Start();
9667 base::RunLoop().Run();
9668
9669 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9670 EXPECT_FALSE(req->response_info().network_accessed);
9671}
9672
9673TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9674 MockHostResolver host_resolver;
9675 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9676 TestURLRequestContext context(true);
9677 context.set_network_delegate(&network_delegate);
9678 context.set_host_resolver(&host_resolver);
9679 host_resolver.rules()->AddSimulatedFailure("*");
9680 context.Init();
9681
9682 TestDelegate d;
9683 scoped_ptr<URLRequest> req(context.CreateRequest(
9684 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9685
9686 EXPECT_FALSE(req->response_info().network_accessed);
9687
9688 req->Start();
9689 base::RunLoop().Run();
9690 EXPECT_TRUE(req->response_info().network_accessed);
9691}
9692
alexanderkcd904b52015-07-24 18:57:229693// Test that URLRequest is canceled correctly and with detached request
9694// URLRequestRedirectJob does not crash in StartAsync.
9695// See http://crbug.com/508900
9696TEST_F(URLRequestTest, URLRequestRedirectJobDetachRequestNoCrash) {
9697 TestDelegate d;
9698 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9699 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
9700
9701 URLRequestRedirectJob* job = new URLRequestRedirectJob(
9702 req.get(), &default_network_delegate_,
9703 GURL("http://this-should-never-be-navigated-to/"),
9704 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp");
9705 AddTestInterceptor()->set_main_intercept_job(job);
9706
9707 req->Start();
9708 req->Cancel();
9709 job->DetachRequest();
9710 base::RunLoop().RunUntilIdle();
9711 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
9712 EXPECT_EQ(0, d.received_redirect_count());
9713}
9714
[email protected]7461a402011-03-24 23:19:519715} // namespace net