blob: 2b6f11f72def6b88f669e72b0ded96d7bb4c16f0 [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
dchengc7eeda422015-12-26 03:56:485#include <utility>
6
[email protected]ea224582008-12-07 20:25:467#include "build/build_config.h"
8
[email protected]9396b252008-09-29 17:29:389#if defined(OS_WIN)
[email protected]d8eb84242010-09-25 02:25:0610#include <windows.h>
[email protected]aa84a7e2012-03-15 21:29:0611#include <shlobj.h>
[email protected]9396b252008-09-29 17:29:3812#endif
13
tbansalea2fb8c2015-05-22 22:23:0014#include <stdint.h>
15
initial.commit586acc5fe2008-07-26 22:42:5216#include <algorithm>
avibf0746c2015-12-09 19:53:1417#include <limits>
initial.commit586acc5fe2008-07-26 22:42:5218
nharperb7441ef2016-01-25 23:54:1419#include "base/base64url.h"
[email protected]218aa6a12011-09-13 17:38:3820#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5821#include "base/compiler_specific.h"
mmenke9f2ec60c2015-06-01 20:59:4722#include "base/files/file_path.h"
thestigd8df0332014-09-04 06:33:2923#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0724#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2825#include "base/format_macros.h"
estark06e0dac2015-08-07 21:56:0126#include "base/json/json_reader.h"
skyostil4891b25b2015-06-11 11:43:4527#include "base/location.h"
Avi Drissman13fc8932015-12-20 04:40:4628#include "base/macros.h"
mmenke19378d22014-09-09 04:12:5929#include "base/memory/scoped_ptr.h"
[email protected]084262c2011-12-01 21:12:4730#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2231#include "base/message_loop/message_loop.h"
initial.commit586acc5fe2008-07-26 22:42:5232#include "base/path_service.h"
mmenkefb18c772015-09-30 22:22:5033#include "base/power_monitor/power_monitor.h"
34#include "base/power_monitor/power_monitor_source.h"
[email protected]255620da2013-08-19 13:14:2935#include "base/run_loop.h"
skyostil4891b25b2015-06-11 11:43:4536#include "base/single_thread_task_runner.h"
[email protected]4dc3ad4f2013-06-11 07:15:5037#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5538#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2239#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2240#include "base/strings/string_util.h"
41#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0542#include "base/strings/utf_string_conversions.h"
tbansalea2fb8c2015-05-22 22:23:0043#include "base/test/histogram_tester.h"
skyostil4891b25b2015-06-11 11:43:4544#include "base/thread_task_runner_handle.h"
estark06e0dac2015-08-07 21:56:0145#include "base/values.h"
mmenkecbc2b712014-10-09 20:29:0746#include "net/base/chunked_upload_data_stream.h"
tfarina43a416b2016-01-06 21:48:0747#include "net/base/directory_listing.h"
mmenkecbc2b712014-10-09 20:29:0748#include "net/base/elements_upload_data_stream.h"
tbansal1c92d5b2015-08-14 20:14:4349#include "net/base/external_estimate_provider.h"
initial.commit586acc5fe2008-07-26 22:42:5250#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2551#include "net/base/load_timing_info.h"
52#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0653#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5254#include "net/base/net_module.h"
tbansalea2fb8c2015-05-22 22:23:0055#include "net/base/network_quality_estimator.h"
[email protected]2ca01e52013-10-31 22:05:1956#include "net/base/request_priority.h"
[email protected]42fdb452012-11-01 12:44:4057#include "net/base/test_data_directory.h"
[email protected]f288ef02012-12-15 20:28:2858#include "net/base/upload_bytes_element_reader.h"
59#include "net/base/upload_data_stream.h"
60#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4461#include "net/base/url_util.h"
[email protected]6e7845ae2013-03-29 21:48:1162#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2463#include "net/cert/mock_cert_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1164#include "net/cert/test_root_certs.h"
eromaned744f32015-04-09 06:35:4965#include "net/cert_net/nss_ocsp.h"
[email protected]aa84a7e2012-03-15 21:29:0666#include "net/cookies/cookie_monster.h"
67#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5268#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5369#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3870#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5271#include "net/http/http_cache.h"
72#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1973#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2574#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2175#include "net/http/http_response_headers.h"
[email protected]e50efea2014-03-24 18:41:0076#include "net/http/http_util.h"
eroman87c53d62015-04-02 06:51:0777#include "net/log/net_log.h"
vishal.b62985ca92015-04-17 08:45:5178#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4679#include "net/log/test_net_log_entry.h"
80#include "net/log/test_net_log_util.h"
[email protected]63de95b2008-12-10 04:11:2781#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1982#include "net/socket/ssl_client_socket.h"
nharperb7441ef2016-01-25 23:54:1483#include "net/ssl/channel_id_service.h"
84#include "net/ssl/default_channel_id_store.h"
davidben8ecc3072014-09-03 23:19:0985#include "net/ssl/ssl_cipher_suite_names.h"
[email protected]536fd0b2013-03-14 17:41:5786#include "net/ssl/ssl_connection_status_flags.h"
tommycli59a63432015-11-06 00:10:5587#include "net/ssl/ssl_server_config.h"
nharperb7441ef2016-01-25 23:54:1488#include "net/ssl/token_binding.h"
[email protected]6e7845ae2013-03-29 21:48:1189#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:3690#include "net/test/embedded_test_server/embedded_test_server.h"
91#include "net/test/embedded_test_server/http_request.h"
92#include "net/test/embedded_test_server/http_response.h"
[email protected]89b32522013-05-07 20:04:2193#include "net/test/spawned_test_server/spawned_test_server.h"
mmenkefb18c772015-09-30 22:22:5094#include "net/test/url_request/url_request_failed_job.h"
[email protected]e0f35c92013-05-08 16:04:3495#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4396#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5297#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:5098#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:1499#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:50100#include "net/url_request/url_request_intercepting_job_factory.h"
101#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49102#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51103#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47104#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44105#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:52106#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15107#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52108
[email protected]02494ec2014-05-07 15:05:29109#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55110#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29111#include "net/url_request/file_protocol_handler.h"
112#include "net/url_request/url_request_file_dir_job.h"
113#endif
114
mmenke9f2ec60c2015-06-01 20:59:47115#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
116#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29117#include "net/url_request/ftp_protocol_handler.h"
118#endif
119
[email protected]dffe8242012-03-20 15:14:27120#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48121#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56122#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27123#include "base/win/windows_version.h"
124#endif
125
[email protected]ad65a3e2013-12-25 18:18:01126using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33127using base::Time;
halton.huoe4e45742014-12-08 07:55:46128using std::string;
[email protected]e1acf6f2008-10-27 20:43:33129
[email protected]7461a402011-03-24 23:19:51130namespace net {
131
initial.commit586acc5fe2008-07-26 22:42:52132namespace {
133
[email protected]42cba2fb2013-03-29 19:58:57134const base::string16 kChrome(ASCIIToUTF16("chrome"));
135const base::string16 kSecret(ASCIIToUTF16("secret"));
136const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44137
mmenke9f2ec60c2015-06-01 20:59:47138const base::FilePath::CharType kTestFilePath[] =
139 FILE_PATH_LITERAL("net/data/url_request_unittest");
140
141#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
142// Test file used in most FTP tests.
143const char kFtpTestFile[] = "BullRunSpeech.txt";
144#endif
145
[email protected]2bba3252013-04-08 19:50:59146// Tests load timing information in the case a fresh connection was used, with
147// no proxy.
[email protected]cba24642014-08-15 20:49:59148void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25149 int connect_timing_flags) {
150 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59151 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25152
153 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
154 EXPECT_FALSE(load_timing_info.request_start.is_null());
155
156 EXPECT_LE(load_timing_info.request_start,
157 load_timing_info.connect_timing.connect_start);
158 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
159 connect_timing_flags);
160 EXPECT_LE(load_timing_info.connect_timing.connect_end,
161 load_timing_info.send_start);
162 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
163 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
164
[email protected]58e32bb2013-01-21 18:23:25165 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
166 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
167}
168
[email protected]2bba3252013-04-08 19:50:59169// Same as above, but with proxy times.
170void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59171 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59172 int connect_timing_flags) {
173 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59174 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59175
176 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
177 EXPECT_FALSE(load_timing_info.request_start.is_null());
178
179 EXPECT_LE(load_timing_info.request_start,
180 load_timing_info.proxy_resolve_start);
181 EXPECT_LE(load_timing_info.proxy_resolve_start,
182 load_timing_info.proxy_resolve_end);
183 EXPECT_LE(load_timing_info.proxy_resolve_end,
184 load_timing_info.connect_timing.connect_start);
185 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
186 connect_timing_flags);
187 EXPECT_LE(load_timing_info.connect_timing.connect_end,
188 load_timing_info.send_start);
189 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
190 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
191}
192
193// Same as above, but with a reused socket and proxy times.
194void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59195 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59196 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59197 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59198
199 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
200 EXPECT_FALSE(load_timing_info.request_start.is_null());
201
202 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
203
204 EXPECT_LE(load_timing_info.request_start,
205 load_timing_info.proxy_resolve_start);
206 EXPECT_LE(load_timing_info.proxy_resolve_start,
207 load_timing_info.proxy_resolve_end);
208 EXPECT_LE(load_timing_info.proxy_resolve_end,
209 load_timing_info.send_start);
210 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
211 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
212}
213
xunjielia6888202015-04-14 21:34:25214#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25215// Tests load timing information in the case of a cache hit, when no cache
216// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17217base::StringPiece TestNetResourceProvider(int key) {
218 return "header";
219}
220
221void FillBuffer(char* buffer, size_t len) {
222 static bool called = false;
223 if (!called) {
224 called = true;
225 int seed = static_cast<int>(Time::Now().ToInternalValue());
226 srand(seed);
227 }
228
229 for (size_t i = 0; i < len; i++) {
230 buffer[i] = static_cast<char>(rand());
231 if (!buffer[i])
232 buffer[i] = 'g';
233 }
234}
xunjielia6888202015-04-14 21:34:25235#endif
[email protected]e3a85452013-11-14 01:46:17236
[email protected]3b23a222013-05-15 21:33:25237void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59238 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25239 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59240 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25241
242 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
243 EXPECT_FALSE(load_timing_info.request_start.is_null());
244
245 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
246 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
247 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
248 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
249
250 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
251 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
252}
253
mmenke9f2ec60c2015-06-01 20:59:47254#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25255// Tests load timing in the case that there is no HTTP response. This can be
256// used to test in the case of errors or non-HTTP requests.
257void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59258 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25259 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59260 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25261
262 // Only the request times should be non-null.
263 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
264 EXPECT_FALSE(load_timing_info.request_start.is_null());
265
266 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
267
268 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
269 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
270 EXPECT_TRUE(load_timing_info.send_start.is_null());
271 EXPECT_TRUE(load_timing_info.send_end.is_null());
272 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
273}
xunjielia6888202015-04-14 21:34:25274#endif
[email protected]58e32bb2013-01-21 18:23:25275
mmenkefb18c772015-09-30 22:22:50276// Test power monitor source that can simulate entering suspend mode. Can't use
277// the one in base/ because it insists on bringing its own MessageLoop.
278class TestPowerMonitorSource : public base::PowerMonitorSource {
279 public:
280 TestPowerMonitorSource() {}
281 ~TestPowerMonitorSource() override {}
282
283 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
284
285 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
286
287 bool IsOnBatteryPowerImpl() override { return false; }
288
289 private:
290 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
291};
292
mmenkeed0498b2015-12-08 23:20:42293// Job that allows monitoring of its priority.
294class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
295 public:
296 // The latest priority of the job is always written to |request_priority_|.
297 PriorityMonitoringURLRequestJob(URLRequest* request,
298 NetworkDelegate* network_delegate,
299 RequestPriority* request_priority)
300 : URLRequestTestJob(request, network_delegate),
301 request_priority_(request_priority) {
302 *request_priority_ = DEFAULT_PRIORITY;
303 }
304
305 void SetPriority(RequestPriority priority) override {
306 *request_priority_ = priority;
307 URLRequestTestJob::SetPriority(priority);
308 }
309
310 private:
311 RequestPriority* const request_priority_;
312};
313
[email protected]71c64f62008-11-15 04:36:51314// Do a case-insensitive search through |haystack| for |needle|.
315bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50316 std::string::const_iterator it = std::search(
317 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
318 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51319 return it != haystack.end();
320}
321
mmenkecbc2b712014-10-09 20:29:07322scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
[email protected]f288ef02012-12-15 20:28:28323 scoped_ptr<UploadElementReader> reader(
324 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48325 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23326}
327
[email protected]96adadb2010-08-28 01:16:17328// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51329void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17330 // -1 means unknown. 0 means no encryption.
331 EXPECT_GT(ssl_info.security_bits, 0);
332
333 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14334 uint16_t cipher_suite =
335 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29336 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17337}
338
[email protected]79e1fd62013-06-20 06:50:04339void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
340 const GURL& host_url) {
341 std::string sent_value;
342
343 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
344 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
345
346 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
347 EXPECT_EQ("keep-alive", sent_value);
348}
349
tommycli59a63432015-11-06 00:10:55350#if !defined(OS_IOS)
[email protected]ede03212012-09-07 12:52:26351bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27352 size_t size = a.size();
353
354 if (size != b.size())
355 return false;
356
357 for (size_t i = 0; i < size; ++i) {
358 if (!a[i].Equals(b[i]))
359 return false;
360 }
361
362 return true;
363}
[email protected]e3a85452013-11-14 01:46:17364#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27365
[email protected]dc5a5cf2012-09-26 02:49:30366// A network delegate that allows the user to choose a subset of request stages
367// to block in. When blocking, the delegate can do one of the following:
368// * synchronously return a pre-specified error code, or
369// * asynchronously return that value via an automatically called callback,
370// or
371// * block and wait for the user to do a callback.
372// Additionally, the user may also specify a redirect URL -- then each request
373// with the current URL different from the redirect target will be redirected
374// to that target, in the on-before-URL-request stage, independent of whether
375// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12376class BlockingNetworkDelegate : public TestNetworkDelegate {
377 public:
[email protected]dc5a5cf2012-09-26 02:49:30378 // Stages in which the delegate can block.
379 enum Stage {
[email protected]9045b8822012-01-13 20:35:35380 NOT_BLOCKED = 0,
381 ON_BEFORE_URL_REQUEST = 1 << 0,
382 ON_BEFORE_SEND_HEADERS = 1 << 1,
383 ON_HEADERS_RECEIVED = 1 << 2,
384 ON_AUTH_REQUIRED = 1 << 3
385 };
386
[email protected]dc5a5cf2012-09-26 02:49:30387 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59388 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30389 enum BlockMode {
390 SYNCHRONOUS, // No callback, returns specified return values.
391 AUTO_CALLBACK, // |this| posts a task to run the callback using the
392 // specified return codes.
393 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
394 // |auth_retval_| are ignored. In every blocking stage the
395 // message loop is quit.
396 };
397
398 // Creates a delegate which does not block at all.
399 explicit BlockingNetworkDelegate(BlockMode block_mode);
400
401 // For users to trigger a callback returning |response|.
402 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
403 // Only call if |block_mode_| == USER_CALLBACK.
404 void DoCallback(int response);
405 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
406
407 // Setters.
408 void set_retval(int retval) {
409 ASSERT_NE(USER_CALLBACK, block_mode_);
410 ASSERT_NE(ERR_IO_PENDING, retval);
411 ASSERT_NE(OK, retval);
412 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35413 }
414
[email protected]dc5a5cf2012-09-26 02:49:30415 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
416 // |auth_credentials_| will be passed with the response.
417 void set_auth_retval(AuthRequiredResponse auth_retval) {
418 ASSERT_NE(USER_CALLBACK, block_mode_);
419 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
420 auth_retval_ = auth_retval;
421 }
422 void set_auth_credentials(const AuthCredentials& auth_credentials) {
423 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35424 }
425
[email protected]dc5a5cf2012-09-26 02:49:30426 void set_redirect_url(const GURL& url) {
427 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35428 }
429
[email protected]dc5a5cf2012-09-26 02:49:30430 void set_block_on(int block_on) {
431 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35432 }
433
[email protected]dc5a5cf2012-09-26 02:49:30434 // Allows the user to check in which state did we block.
435 Stage stage_blocked_for_callback() const {
436 EXPECT_EQ(USER_CALLBACK, block_mode_);
437 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35438 }
439
440 private:
[email protected]dc5a5cf2012-09-26 02:49:30441 void RunCallback(int response, const CompletionCallback& callback);
442 void RunAuthCallback(AuthRequiredResponse response,
443 const AuthCallback& callback);
444
[email protected]9045b8822012-01-13 20:35:35445 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20446 int OnBeforeURLRequest(URLRequest* request,
447 const CompletionCallback& callback,
448 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35449
dchengb03027d2014-10-21 12:00:20450 int OnBeforeSendHeaders(URLRequest* request,
451 const CompletionCallback& callback,
452 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35453
dchengb03027d2014-10-21 12:00:20454 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35455 URLRequest* request,
456 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32457 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16458 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13459 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35460
dchengb03027d2014-10-21 12:00:20461 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35462 URLRequest* request,
463 const AuthChallengeInfo& auth_info,
464 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13465 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35466
[email protected]dc5a5cf2012-09-26 02:49:30467 // Resets the callbacks and |stage_blocked_for_callback_|.
468 void Reset();
[email protected]9045b8822012-01-13 20:35:35469
[email protected]dc5a5cf2012-09-26 02:49:30470 // Checks whether we should block in |stage|. If yes, returns an error code
471 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
472 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
473
474 // Configuration parameters, can be adjusted by public methods:
475 const BlockMode block_mode_;
476
477 // Values returned on blocking stages when mode is SYNCHRONOUS or
478 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
479 int retval_; // To be returned in non-auth stages.
480 AuthRequiredResponse auth_retval_;
481
[email protected]5f714132014-03-26 10:41:16482 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30483 int block_on_; // Bit mask: in which stages to block.
484
485 // |auth_credentials_| will be copied to |*target_auth_credential_| on
486 // callback.
487 AuthCredentials auth_credentials_;
488 AuthCredentials* target_auth_credentials_;
489
490 // Internal variables, not set by not the user:
491 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
492 // USER_CALLBACK).
493 Stage stage_blocked_for_callback_;
494
495 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35496 CompletionCallback callback_;
497 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30498
499 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
500
501 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35502};
503
[email protected]dc5a5cf2012-09-26 02:49:30504BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
505 : block_mode_(block_mode),
506 retval_(OK),
507 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
508 block_on_(0),
509 target_auth_credentials_(NULL),
510 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32511 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30512}
513
514void BlockingNetworkDelegate::DoCallback(int response) {
515 ASSERT_EQ(USER_CALLBACK, block_mode_);
516 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
517 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
518 CompletionCallback callback = callback_;
519 Reset();
520 RunCallback(response, callback);
521}
522
523void BlockingNetworkDelegate::DoAuthCallback(
524 NetworkDelegate::AuthRequiredResponse response) {
525 ASSERT_EQ(USER_CALLBACK, block_mode_);
526 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
527 AuthCallback auth_callback = auth_callback_;
528 Reset();
529 RunAuthCallback(response, auth_callback);
530}
531
532void BlockingNetworkDelegate::RunCallback(int response,
533 const CompletionCallback& callback) {
534 callback.Run(response);
535}
536
537void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
538 const AuthCallback& callback) {
539 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
540 ASSERT_TRUE(target_auth_credentials_ != NULL);
541 *target_auth_credentials_ = auth_credentials_;
542 }
543 callback.Run(response);
544}
545
546int BlockingNetworkDelegate::OnBeforeURLRequest(
547 URLRequest* request,
548 const CompletionCallback& callback,
549 GURL* new_url) {
550 if (redirect_url_ == request->url())
551 return OK; // We've already seen this request and redirected elsewhere.
552
553 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
554
555 if (!redirect_url_.is_empty())
556 *new_url = redirect_url_;
557
558 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
559}
560
561int BlockingNetworkDelegate::OnBeforeSendHeaders(
562 URLRequest* request,
563 const CompletionCallback& callback,
564 HttpRequestHeaders* headers) {
565 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
566
567 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
568}
569
570int BlockingNetworkDelegate::OnHeadersReceived(
571 URLRequest* request,
572 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32573 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16574 scoped_refptr<HttpResponseHeaders>* override_response_headers,
575 GURL* allowed_unsafe_redirect_url) {
576 TestNetworkDelegate::OnHeadersReceived(request,
577 callback,
578 original_response_headers,
579 override_response_headers,
580 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30581
582 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
583}
584
585NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
586 URLRequest* request,
587 const AuthChallengeInfo& auth_info,
588 const AuthCallback& callback,
589 AuthCredentials* credentials) {
590 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
591 credentials);
592 // Check that the user has provided callback for the previous blocked stage.
593 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
594
595 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
596 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
597 }
598
599 target_auth_credentials_ = credentials;
600
601 switch (block_mode_) {
602 case SYNCHRONOUS:
603 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
604 *target_auth_credentials_ = auth_credentials_;
605 return auth_retval_;
606
607 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45608 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30609 FROM_HERE,
610 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
611 weak_factory_.GetWeakPtr(), auth_retval_, callback));
612 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
613
614 case USER_CALLBACK:
615 auth_callback_ = callback;
616 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45617 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17618 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30619 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
620 }
621 NOTREACHED();
622 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
623}
624
625void BlockingNetworkDelegate::Reset() {
626 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
627 stage_blocked_for_callback_ = NOT_BLOCKED;
628 callback_.Reset();
629 auth_callback_.Reset();
630}
631
632int BlockingNetworkDelegate::MaybeBlockStage(
633 BlockingNetworkDelegate::Stage stage,
634 const CompletionCallback& callback) {
635 // Check that the user has provided callback for the previous blocked stage.
636 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
637
638 if ((block_on_ & stage) == 0) {
639 return OK;
640 }
641
642 switch (block_mode_) {
643 case SYNCHRONOUS:
644 EXPECT_NE(OK, retval_);
645 return retval_;
646
647 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45648 base::ThreadTaskRunnerHandle::Get()->PostTask(
649 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
650 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30651 return ERR_IO_PENDING;
652
653 case USER_CALLBACK:
654 callback_ = callback;
655 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45656 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17657 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30658 return ERR_IO_PENDING;
659 }
660 NOTREACHED();
661 return 0;
662}
663
[email protected]d5a4dd62012-05-23 01:41:04664class TestURLRequestContextWithProxy : public TestURLRequestContext {
665 public:
666 // Does not own |delegate|.
667 TestURLRequestContextWithProxy(const std::string& proxy,
668 NetworkDelegate* delegate)
669 : TestURLRequestContext(true) {
670 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
671 set_network_delegate(delegate);
672 Init();
673 }
dchengb03027d2014-10-21 12:00:20674 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04675};
676
estark06e0dac2015-08-07 21:56:01677// A mock ReportSender that just remembers the latest report
678// URI and report to be sent.
679class MockCertificateReportSender
680 : public TransportSecurityState::ReportSender {
681 public:
682 MockCertificateReportSender() {}
683 ~MockCertificateReportSender() override {}
684
685 void Send(const GURL& report_uri, const std::string& report) override {
686 latest_report_uri_ = report_uri;
687 latest_report_ = report;
688 }
689
690 const GURL& latest_report_uri() { return latest_report_uri_; }
691 const std::string& latest_report() { return latest_report_; }
692
693 private:
694 GURL latest_report_uri_;
695 std::string latest_report_;
696};
697
estarkcd39c11f2015-10-19 19:46:36698class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
699 public:
700 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
jww79aceda2015-12-07 01:56:34701 bool OnAreStrictSecureCookiesEnabled() const override { return true; }
estarkcd39c11f2015-10-19 19:46:36702};
703
[email protected]d5a4dd62012-05-23 01:41:04704} // namespace
705
[email protected]a592c0432012-12-01 18:10:29706// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48707class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00708 public:
[email protected]ef2bf422012-05-11 03:27:09709 URLRequestTest() : default_context_(true) {
710 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25711 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50712 job_factory_impl_ = new URLRequestJobFactoryImpl();
713 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50714 }
bengr1bf8e942014-11-07 01:36:50715
dcheng67be2b1f2014-10-27 21:47:29716 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18717 // URLRequestJobs may post clean-up tasks on destruction.
718 base::RunLoop().RunUntilIdle();
719 }
[email protected]87a09a92011-07-14 15:50:50720
dcheng2339883c2014-12-23 00:23:05721 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50722 SetUpFactory();
723 default_context_.set_job_factory(job_factory_.get());
724 default_context_.Init();
725 PlatformTest::SetUp();
726 }
727
728 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20729 job_factory_impl_->SetProtocolHandler(
730 "data", make_scoped_ptr(new DataProtocolHandler));
bengr1bf8e942014-11-07 01:36:50731#if !defined(DISABLE_FILE_SUPPORT)
732 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:20733 "file", make_scoped_ptr(new FileProtocolHandler(
734 base::ThreadTaskRunnerHandle::Get())));
bengr1bf8e942014-11-07 01:36:50735#endif
736 }
737
738 TestNetworkDelegate* default_network_delegate() {
739 return &default_network_delegate_;
740 }
741
742 const TestURLRequestContext& default_context() const {
743 return default_context_;
744 }
745
746
[email protected]3c5ca8c2011-09-29 01:14:51747 // Adds the TestJobInterceptor to the default context.
748 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23749 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20750 job_factory_impl_->SetProtocolHandler("http", nullptr);
751 job_factory_impl_->SetProtocolHandler("http",
752 make_scoped_ptr(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23753 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51754 }
755
[email protected]87a09a92011-07-14 15:50:50756 protected:
vishal.b62985ca92015-04-17 08:45:51757 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24758 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50759 URLRequestJobFactoryImpl* job_factory_impl_;
760 scoped_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09761 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48762};
763
[email protected]316c1e5e2012-09-12 15:17:44764TEST_F(URLRequestTest, AboutBlankTest) {
765 TestDelegate d;
766 {
[email protected]f7022f32014-08-21 16:32:19767 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36768 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44769
[email protected]f7022f32014-08-21 16:32:19770 r->Start();
771 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44772
[email protected]255620da2013-08-19 13:14:29773 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44774
[email protected]f7022f32014-08-21 16:32:19775 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44776 EXPECT_FALSE(d.received_data_before_response());
777 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19778 EXPECT_EQ("", r->GetSocketAddress().host());
779 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04780
781 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19782 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44783 }
784}
785
786TEST_F(URLRequestTest, DataURLImageTest) {
787 TestDelegate d;
788 {
789 // Use our nice little Chrome logo.
[email protected]f7022f32014-08-21 16:32:19790 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:19791 GURL(
davidben151423e2015-03-23 18:48:36792 "data:image/png;base64,"
793 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
794 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
795 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
796 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
797 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
798 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
799 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
800 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
801 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
802 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
803 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
804 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
805 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
806 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
807 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
808 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
809 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
810 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
811 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
812 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44813
[email protected]f7022f32014-08-21 16:32:19814 r->Start();
815 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44816
[email protected]255620da2013-08-19 13:14:29817 base::RunLoop().Run();
[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_FALSE(d.received_data_before_response());
821 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19822 EXPECT_EQ("", r->GetSocketAddress().host());
823 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04824
825 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19826 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44827 }
828}
829
[email protected]5ecf7cb282014-05-11 01:49:55830#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44831TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15832 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44833 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]316c1e5e2012-09-12 15:17:44840
[email protected]f7022f32014-08-21 16:32:19841 r->Start();
842 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44843
[email protected]255620da2013-08-19 13:14:29844 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44845
avibf0746c2015-12-09 19:53:14846 int64_t file_size = -1;
[email protected]56285702013-12-04 18:22:49847 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44848
[email protected]f7022f32014-08-21 16:32:19849 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44850 EXPECT_EQ(1, d.response_started_count());
851 EXPECT_FALSE(d.received_data_before_response());
852 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19853 EXPECT_EQ("", r->GetSocketAddress().host());
854 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04855
856 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19857 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44858 }
859}
860
[email protected]ba40bb762012-12-17 07:11:04861TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15862 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04863 PathService::Get(base::FILE_EXE, &app_path);
864 GURL app_url = FilePathToFileURL(app_path);
865
866 TestDelegate d;
867 {
davidben151423e2015-03-23 18:48:36868 scoped_ptr<URLRequest> r(
869 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04870
[email protected]f7022f32014-08-21 16:32:19871 r->Start();
872 EXPECT_TRUE(r->is_pending());
873 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04874 }
[email protected]79e1fd62013-06-20 06:50:04875 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04876 // destroyed.
[email protected]255620da2013-08-19 13:14:29877 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04878}
879
[email protected]316c1e5e2012-09-12 15:17:44880TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
881 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17882 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44883 FillBuffer(buffer.get(), buffer_size);
884
[email protected]6cdfd7f2013-02-08 20:40:15885 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52886 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44887 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30888 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44889
avibf0746c2015-12-09 19:53:14890 int64_t file_size;
[email protected]56285702013-12-04 18:22:49891 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44892
893 const size_t first_byte_position = 500;
894 const size_t last_byte_position = buffer_size - first_byte_position;
895 const size_t content_length = last_byte_position - first_byte_position + 1;
896 std::string partial_buffer_string(buffer.get() + first_byte_position,
897 buffer.get() + last_byte_position + 1);
898
899 TestDelegate d;
900 {
davidben151423e2015-03-23 18:48:36901 scoped_ptr<URLRequest> r(
902 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44903
904 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38905 headers.SetHeader(
906 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59907 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38908 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19909 r->SetExtraRequestHeaders(headers);
910 r->Start();
911 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44912
[email protected]255620da2013-08-19 13:14:29913 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19914 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44915 EXPECT_EQ(1, d.response_started_count());
916 EXPECT_FALSE(d.received_data_before_response());
917 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
918 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
919 EXPECT_TRUE(partial_buffer_string == d.data_received());
920 }
921
[email protected]dd3aa792013-07-16 19:10:23922 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44923}
924
925TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
926 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17927 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44928 FillBuffer(buffer.get(), buffer_size);
929
[email protected]6cdfd7f2013-02-08 20:40:15930 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52931 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44932 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30933 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44934
avibf0746c2015-12-09 19:53:14935 int64_t file_size;
[email protected]56285702013-12-04 18:22:49936 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44937
938 const size_t first_byte_position = 500;
939 const size_t last_byte_position = buffer_size - 1;
940 const size_t content_length = last_byte_position - first_byte_position + 1;
941 std::string partial_buffer_string(buffer.get() + first_byte_position,
942 buffer.get() + last_byte_position + 1);
943
944 TestDelegate d;
945 {
davidben151423e2015-03-23 18:48:36946 scoped_ptr<URLRequest> r(
947 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44948
949 HttpRequestHeaders headers;
950 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59951 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38952 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19953 r->SetExtraRequestHeaders(headers);
954 r->Start();
955 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44956
[email protected]255620da2013-08-19 13:14:29957 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19958 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44959 EXPECT_EQ(1, d.response_started_count());
960 EXPECT_FALSE(d.received_data_before_response());
961 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
962 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
963 EXPECT_TRUE(partial_buffer_string == d.data_received());
964 }
965
[email protected]dd3aa792013-07-16 19:10:23966 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44967}
968
969TEST_F(URLRequestTest, FileTestMultipleRanges) {
970 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17971 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44972 FillBuffer(buffer.get(), buffer_size);
973
[email protected]6cdfd7f2013-02-08 20:40:15974 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52975 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44976 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30977 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44978
avibf0746c2015-12-09 19:53:14979 int64_t file_size;
[email protected]56285702013-12-04 18:22:49980 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44981
982 TestDelegate d;
983 {
davidben151423e2015-03-23 18:48:36984 scoped_ptr<URLRequest> r(
985 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44986
987 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38988 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19989 r->SetExtraRequestHeaders(headers);
990 r->Start();
991 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44992
[email protected]255620da2013-08-19 13:14:29993 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44994 EXPECT_TRUE(d.request_failed());
995 }
996
[email protected]dd3aa792013-07-16 19:10:23997 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44998}
999
[email protected]3ca8b362013-11-11 22:18:071000TEST_F(URLRequestTest, AllowFileURLs) {
1001 base::ScopedTempDir temp_dir;
1002 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1003 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:521004 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:071005 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:301006 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:591007 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071008
1009 {
1010 TestDelegate d;
1011 TestNetworkDelegate network_delegate;
1012 network_delegate.set_can_access_files(true);
1013 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:361014 scoped_ptr<URLRequest> r(
1015 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191016 r->Start();
[email protected]3ca8b362013-11-11 22:18:071017 base::RunLoop().Run();
1018 EXPECT_FALSE(d.request_failed());
1019 EXPECT_EQ(test_data, d.data_received());
1020 }
1021
1022 {
1023 TestDelegate d;
1024 TestNetworkDelegate network_delegate;
1025 network_delegate.set_can_access_files(false);
1026 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:361027 scoped_ptr<URLRequest> r(
1028 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191029 r->Start();
[email protected]3ca8b362013-11-11 22:18:071030 base::RunLoop().Run();
1031 EXPECT_TRUE(d.request_failed());
1032 EXPECT_EQ("", d.data_received());
1033 }
1034}
1035
[email protected]316c1e5e2012-09-12 15:17:441036
1037TEST_F(URLRequestTest, FileDirCancelTest) {
1038 // Put in mock resource provider.
1039 NetModule::SetResourceProvider(TestNetResourceProvider);
1040
1041 TestDelegate d;
1042 {
[email protected]6cdfd7f2013-02-08 20:40:151043 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441044 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1045 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1046 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1047
[email protected]f7022f32014-08-21 16:32:191048 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361049 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191050 req->Start();
1051 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441052
1053 d.set_cancel_in_received_data_pending(true);
1054
[email protected]255620da2013-08-19 13:14:291055 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441056 }
1057
1058 // Take out mock resource provider.
1059 NetModule::SetResourceProvider(NULL);
1060}
1061
[email protected]5f9581402013-10-30 13:08:321062TEST_F(URLRequestTest, FileDirOutputSanity) {
1063 // Verify the general sanity of the the output of the file:
1064 // directory lister by checking for the output of a known existing
1065 // file.
1066 const char sentinel_name[] = "filedir-sentinel";
1067
1068 base::FilePath path;
1069 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471070 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321071
1072 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191073 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361074 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191075 req->Start();
[email protected]5f9581402013-10-30 13:08:321076 base::RunLoop().Run();
1077
1078 // Generate entry for the sentinel file.
1079 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581080 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491081 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321082 EXPECT_GT(info.size, 0);
1083 std::string sentinel_output = GetDirectoryListingEntry(
1084 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1085 std::string(sentinel_name),
1086 false /* is_dir */,
1087 info.size,
1088 info.last_modified);
1089
1090 ASSERT_LT(0, d.bytes_received());
1091 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191092 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:321093 // Check for the entry generated for the "sentinel" file.
1094 const std::string& data = d.data_received();
1095 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1096}
1097
[email protected]316c1e5e2012-09-12 15:17:441098TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1099 // There is an implicit redirect when loading a file path that matches a
1100 // directory and does not end with a slash. Ensure that following such
1101 // redirects does not crash. See http://crbug.com/18686.
1102
[email protected]6cdfd7f2013-02-08 20:40:151103 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441104 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471105 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441106
1107 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191108 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361109 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191110 req->Start();
[email protected]255620da2013-08-19 13:14:291111 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441112
1113 ASSERT_EQ(1, d.received_redirect_count());
1114 ASSERT_LT(0, d.bytes_received());
1115 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191116 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441117}
1118
1119#if defined(OS_WIN)
1120// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1121TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1122 TestDelegate d;
davidben151423e2015-03-23 18:48:361123 scoped_ptr<URLRequest> req(
1124 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191125 req->Start();
[email protected]255620da2013-08-19 13:14:291126 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441127
1128 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191129 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441130}
[email protected]5ecf7cb282014-05-11 01:49:551131#endif // defined(OS_WIN)
1132
1133#endif // !defined(DISABLE_FILE_SUPPORT)
1134
1135TEST_F(URLRequestTest, InvalidUrlTest) {
1136 TestDelegate d;
1137 {
[email protected]f7022f32014-08-21 16:32:191138 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361139 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551140
[email protected]f7022f32014-08-21 16:32:191141 r->Start();
1142 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551143
1144 base::RunLoop().Run();
1145 EXPECT_TRUE(d.request_failed());
1146 }
1147}
1148
jochen0e3b3a62014-09-16 18:31:231149TEST_F(URLRequestTest, InvalidReferrerTest) {
1150 TestURLRequestContext context;
1151 TestNetworkDelegate network_delegate;
1152 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1153 context.set_network_delegate(&network_delegate);
1154 TestDelegate d;
davidben151423e2015-03-23 18:48:361155 scoped_ptr<URLRequest> req(
1156 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231157 req->SetReferrer("https://somewhere.com/");
1158
1159 req->Start();
1160 base::RunLoop().Run();
1161 EXPECT_TRUE(d.request_failed());
1162}
1163
[email protected]5ecf7cb282014-05-11 01:49:551164#if defined(OS_WIN)
1165TEST_F(URLRequestTest, ResolveShortcutTest) {
1166 base::FilePath app_path;
1167 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471168 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551169 app_path = app_path.AppendASCII("with-headers.html");
1170
1171 std::wstring lnk_path = app_path.value() + L".lnk";
1172
1173 base::win::ScopedCOMInitializer com_initializer;
1174
1175 // Temporarily create a shortcut for test
1176 {
1177 base::win::ScopedComPtr<IShellLink> shell;
1178 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1179 CLSCTX_INPROC_SERVER)));
1180 base::win::ScopedComPtr<IPersistFile> persist;
1181 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1182 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1183 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1184 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1185 }
1186
1187 TestDelegate d;
1188 {
[email protected]f7022f32014-08-21 16:32:191189 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361190 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551191
[email protected]f7022f32014-08-21 16:32:191192 r->Start();
1193 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551194
1195 base::RunLoop().Run();
1196
1197 WIN32_FILE_ATTRIBUTE_DATA data;
1198 GetFileAttributesEx(app_path.value().c_str(),
1199 GetFileExInfoStandard, &data);
1200 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1201 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1202 FILE_ATTRIBUTE_NORMAL, NULL);
1203 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1204 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1205 DWORD read_size;
1206 BOOL result;
1207 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1208 &read_size, NULL);
1209 std::string content(buffer.get(), read_size);
1210 CloseHandle(file);
1211
[email protected]f7022f32014-08-21 16:32:191212 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551213 EXPECT_EQ(1, d.received_redirect_count());
1214 EXPECT_EQ(content, d.data_received());
1215 }
1216
1217 // Clean the shortcut
1218 DeleteFile(lnk_path.c_str());
1219}
1220#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441221
1222// Custom URLRequestJobs for use with interceptor tests
1223class RestartTestJob : public URLRequestTestJob {
1224 public:
1225 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1226 : URLRequestTestJob(request, network_delegate, true) {}
1227 protected:
dchengb03027d2014-10-21 12:00:201228 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441229 private:
dchengb03027d2014-10-21 12:00:201230 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441231};
1232
1233class CancelTestJob : public URLRequestTestJob {
1234 public:
1235 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1236 : URLRequestTestJob(request, network_delegate, true) {}
1237 protected:
dchengb03027d2014-10-21 12:00:201238 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441239 private:
dchengb03027d2014-10-21 12:00:201240 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441241};
1242
1243class CancelThenRestartTestJob : public URLRequestTestJob {
1244 public:
1245 explicit CancelThenRestartTestJob(URLRequest* request,
1246 NetworkDelegate* network_delegate)
1247 : URLRequestTestJob(request, network_delegate, true) {
1248 }
1249 protected:
dchengb03027d2014-10-21 12:00:201250 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441251 request_->Cancel();
1252 this->NotifyRestartRequired();
1253 }
1254 private:
dchengb03027d2014-10-21 12:00:201255 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441256};
1257
bengr1bf8e942014-11-07 01:36:501258// An Interceptor for use with interceptor tests.
1259class MockURLRequestInterceptor : public URLRequestInterceptor {
1260 public:
1261 // Static getters for canned response header and data strings.
1262 static std::string ok_data() {
1263 return URLRequestTestJob::test_data_1();
1264 }
1265
1266 static std::string ok_headers() {
1267 return URLRequestTestJob::test_headers();
1268 }
1269
1270 static std::string redirect_data() {
1271 return std::string();
1272 }
1273
1274 static std::string redirect_headers() {
1275 return URLRequestTestJob::test_redirect_headers();
1276 }
1277
1278 static std::string error_data() {
1279 return std::string("ohhh nooooo mr. bill!");
1280 }
1281
1282 static std::string error_headers() {
1283 return URLRequestTestJob::test_error_headers();
1284 }
1285
1286 MockURLRequestInterceptor()
1287 : intercept_main_request_(false), restart_main_request_(false),
1288 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1289 simulate_main_network_error_(false),
1290 intercept_redirect_(false), cancel_redirect_request_(false),
1291 intercept_final_response_(false), cancel_final_request_(false),
1292 use_url_request_http_job_(false),
1293 did_intercept_main_(false), did_restart_main_(false),
1294 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1295 did_simulate_error_main_(false),
1296 did_intercept_redirect_(false), did_cancel_redirect_(false),
1297 did_intercept_final_(false), did_cancel_final_(false) {
1298 }
1299
1300 ~MockURLRequestInterceptor() override {
1301 }
1302
1303 // URLRequestInterceptor implementation:
1304 URLRequestJob* MaybeInterceptRequest(
1305 URLRequest* request,
1306 NetworkDelegate* network_delegate) const override {
1307 if (restart_main_request_) {
1308 restart_main_request_ = false;
1309 did_restart_main_ = true;
1310 return new RestartTestJob(request, network_delegate);
1311 }
1312 if (cancel_main_request_) {
1313 cancel_main_request_ = false;
1314 did_cancel_main_ = true;
1315 return new CancelTestJob(request, network_delegate);
1316 }
1317 if (cancel_then_restart_main_request_) {
1318 cancel_then_restart_main_request_ = false;
1319 did_cancel_then_restart_main_ = true;
1320 return new CancelThenRestartTestJob(request, network_delegate);
1321 }
1322 if (simulate_main_network_error_) {
1323 simulate_main_network_error_ = false;
1324 did_simulate_error_main_ = true;
1325 if (use_url_request_http_job_) {
1326 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1327 }
1328 // This job will result in error since the requested URL is not one of the
1329 // URLs supported by these tests.
1330 return new URLRequestTestJob(request, network_delegate, true);
1331 }
1332 if (!intercept_main_request_)
1333 return nullptr;
1334 intercept_main_request_ = false;
1335 did_intercept_main_ = true;
1336 URLRequestTestJob* job = new URLRequestTestJob(request,
1337 network_delegate,
1338 main_headers_,
1339 main_data_,
1340 true);
1341 job->set_load_timing_info(main_request_load_timing_info_);
1342 return job;
1343 }
1344
1345 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1346 NetworkDelegate* network_delegate,
1347 const GURL& location) const override {
1348 if (cancel_redirect_request_) {
1349 cancel_redirect_request_ = false;
1350 did_cancel_redirect_ = true;
1351 return new CancelTestJob(request, network_delegate);
1352 }
1353 if (!intercept_redirect_)
1354 return nullptr;
1355 intercept_redirect_ = false;
1356 did_intercept_redirect_ = true;
1357 if (use_url_request_http_job_) {
1358 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1359 }
1360 return new URLRequestTestJob(request,
1361 network_delegate,
1362 redirect_headers_,
1363 redirect_data_,
1364 true);
1365 }
1366
1367 URLRequestJob* MaybeInterceptResponse(
1368 URLRequest* request,
1369 NetworkDelegate* network_delegate) const override {
1370 if (cancel_final_request_) {
1371 cancel_final_request_ = false;
1372 did_cancel_final_ = true;
1373 return new CancelTestJob(request, network_delegate);
1374 }
1375 if (!intercept_final_response_)
1376 return nullptr;
1377 intercept_final_response_ = false;
1378 did_intercept_final_ = true;
1379 if (use_url_request_http_job_) {
1380 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1381 }
1382 return new URLRequestTestJob(request,
1383 network_delegate,
1384 final_headers_,
1385 final_data_,
1386 true);
1387 }
1388
1389 void set_intercept_main_request(bool intercept_main_request) {
1390 intercept_main_request_ = intercept_main_request;
1391 }
1392
1393 void set_main_headers(const std::string& main_headers) {
1394 main_headers_ = main_headers;
1395 }
1396
1397 void set_main_data(const std::string& main_data) {
1398 main_data_ = main_data;
1399 }
1400
1401 void set_main_request_load_timing_info(
1402 const LoadTimingInfo& main_request_load_timing_info) {
1403 main_request_load_timing_info_ = main_request_load_timing_info;
1404 }
1405
1406 void set_restart_main_request(bool restart_main_request) {
1407 restart_main_request_ = restart_main_request;
1408 }
1409
1410 void set_cancel_main_request(bool cancel_main_request) {
1411 cancel_main_request_ = cancel_main_request;
1412 }
1413
1414 void set_cancel_then_restart_main_request(
1415 bool cancel_then_restart_main_request) {
1416 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1417 }
1418
1419 void set_simulate_main_network_error(bool simulate_main_network_error) {
1420 simulate_main_network_error_ = simulate_main_network_error;
1421 }
1422
1423 void set_intercept_redirect(bool intercept_redirect) {
1424 intercept_redirect_ = intercept_redirect;
1425 }
1426
1427 void set_redirect_headers(const std::string& redirect_headers) {
1428 redirect_headers_ = redirect_headers;
1429 }
1430
1431 void set_redirect_data(const std::string& redirect_data) {
1432 redirect_data_ = redirect_data;
1433 }
1434
1435 void set_cancel_redirect_request(bool cancel_redirect_request) {
1436 cancel_redirect_request_ = cancel_redirect_request;
1437 }
1438
1439 void set_intercept_final_response(bool intercept_final_response) {
1440 intercept_final_response_ = intercept_final_response;
1441 }
1442
1443 void set_final_headers(const std::string& final_headers) {
1444 final_headers_ = final_headers;
1445 }
1446
1447 void set_final_data(const std::string& final_data) {
1448 final_data_ = final_data;
1449 }
1450
1451 void set_cancel_final_request(bool cancel_final_request) {
1452 cancel_final_request_ = cancel_final_request;
1453 }
1454
1455 void set_use_url_request_http_job(bool use_url_request_http_job) {
1456 use_url_request_http_job_ = use_url_request_http_job;
1457 }
1458
1459 bool did_intercept_main() const {
1460 return did_intercept_main_;
1461 }
1462
1463 bool did_restart_main() const {
1464 return did_restart_main_;
1465 }
1466
1467 bool did_cancel_main() const {
1468 return did_cancel_main_;
1469 }
1470
1471 bool did_cancel_then_restart_main() const {
1472 return did_cancel_then_restart_main_;
1473 }
1474
1475 bool did_simulate_error_main() const {
1476 return did_simulate_error_main_;
1477 }
1478
1479 bool did_intercept_redirect() const {
1480 return did_intercept_redirect_;
1481 }
1482
1483 bool did_cancel_redirect() const {
1484 return did_cancel_redirect_;
1485 }
1486
1487 bool did_intercept_final() const {
1488 return did_intercept_final_;
1489 }
1490
1491 bool did_cancel_final() const {
1492 return did_cancel_final_;
1493 }
1494
1495 private:
1496 // Indicate whether to intercept the main request, and if so specify the
1497 // response to return and the LoadTimingInfo to use.
1498 mutable bool intercept_main_request_;
1499 mutable std::string main_headers_;
1500 mutable std::string main_data_;
1501 mutable LoadTimingInfo main_request_load_timing_info_;
1502
1503 // These indicate actions that can be taken within MaybeInterceptRequest.
1504 mutable bool restart_main_request_;
1505 mutable bool cancel_main_request_;
1506 mutable bool cancel_then_restart_main_request_;
1507 mutable bool simulate_main_network_error_;
1508
1509 // Indicate whether to intercept redirects, and if so specify the response to
1510 // return.
1511 mutable bool intercept_redirect_;
1512 mutable std::string redirect_headers_;
1513 mutable std::string redirect_data_;
1514
1515 // Cancel the request within MaybeInterceptRedirect.
1516 mutable bool cancel_redirect_request_;
1517
1518 // Indicate whether to intercept the final response, and if so specify the
1519 // response to return.
1520 mutable bool intercept_final_response_;
1521 mutable std::string final_headers_;
1522 mutable std::string final_data_;
1523
1524 // Cancel the final request within MaybeInterceptResponse.
1525 mutable bool cancel_final_request_;
1526
1527 // Instruct the interceptor to use a real URLRequestHTTPJob.
1528 mutable bool use_url_request_http_job_;
1529
1530 // These indicate if the interceptor did something or not.
1531 mutable bool did_intercept_main_;
1532 mutable bool did_restart_main_;
1533 mutable bool did_cancel_main_;
1534 mutable bool did_cancel_then_restart_main_;
1535 mutable bool did_simulate_error_main_;
1536 mutable bool did_intercept_redirect_;
1537 mutable bool did_cancel_redirect_;
1538 mutable bool did_intercept_final_;
1539 mutable bool did_cancel_final_;
1540};
1541
1542// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1543class URLRequestInterceptorTest : public URLRequestTest {
1544 public:
1545 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1546 }
1547
1548 ~URLRequestInterceptorTest() override {
1549 // URLRequestJobs may post clean-up tasks on destruction.
1550 base::RunLoop().RunUntilIdle();
1551 }
1552
1553 void SetUpFactory() override {
1554 interceptor_ = new MockURLRequestInterceptor();
1555 job_factory_.reset(new URLRequestInterceptingJobFactory(
dchengc7eeda422015-12-26 03:56:481556 std::move(job_factory_), make_scoped_ptr(interceptor_)));
bengr1bf8e942014-11-07 01:36:501557 }
1558
1559 MockURLRequestInterceptor* interceptor() const {
1560 return interceptor_;
1561 }
1562
1563 private:
1564 MockURLRequestInterceptor* interceptor_;
1565};
1566
1567TEST_F(URLRequestInterceptorTest, Intercept) {
1568 // Intercept the main request and respond with a simple response.
1569 interceptor()->set_intercept_main_request(true);
1570 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1571 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591572 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501573 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361574 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501575 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1576 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1577 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1578 req->SetUserData(nullptr, user_data0);
1579 req->SetUserData(&user_data1, user_data1);
1580 req->SetUserData(&user_data2, user_data2);
1581 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191582 req->Start();
[email protected]255620da2013-08-19 13:14:291583 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591584
bengr1bf8e942014-11-07 01:36:501585 // Make sure we can retrieve our specific user data.
1586 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1587 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1588 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591589
bengr1bf8e942014-11-07 01:36:501590 // Check that we got one good response.
1591 EXPECT_TRUE(req->status().is_success());
1592 EXPECT_EQ(200, req->response_headers()->response_code());
1593 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1594 EXPECT_EQ(1, d.response_started_count());
1595 EXPECT_EQ(0, d.received_redirect_count());
1596}
[email protected]2bba3252013-04-08 19:50:591597
bengr1bf8e942014-11-07 01:36:501598TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1599 // Intercept the main request and respond with a redirect.
1600 interceptor()->set_intercept_main_request(true);
1601 interceptor()->set_main_headers(
1602 MockURLRequestInterceptor::redirect_headers());
1603 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1604
1605 // Intercept that redirect and respond with a final OK response.
1606 interceptor()->set_intercept_redirect(true);
1607 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1608 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1609
1610 TestDelegate d;
1611 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361612 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501613 req->set_method("GET");
1614 req->Start();
1615 base::RunLoop().Run();
1616
1617 // Check that the interceptor got called as expected.
1618 EXPECT_TRUE(interceptor()->did_intercept_main());
1619 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1620
1621 // Check that we got one good response.
1622 EXPECT_TRUE(req->status().is_success());
1623 if (req->status().is_success())
1624 EXPECT_EQ(200, req->response_headers()->response_code());
1625
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, InterceptServerError) {
1632 // Intercept the main request to generate a server error response.
1633 interceptor()->set_intercept_main_request(true);
1634 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1635 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1636
1637 // Intercept that error and respond with an OK response.
1638 interceptor()->set_intercept_final_response(true);
1639 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1640 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1641
1642 TestDelegate d;
1643 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361644 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501645 req->set_method("GET");
1646 req->Start();
1647 base::RunLoop().Run();
1648
1649 // Check that the interceptor got called as expected.
1650 EXPECT_TRUE(interceptor()->did_intercept_main());
1651 EXPECT_TRUE(interceptor()->did_intercept_final());
1652
1653 // Check that we got one good response.
1654 EXPECT_TRUE(req->status().is_success());
1655 EXPECT_EQ(200, req->response_headers()->response_code());
1656 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1657 EXPECT_EQ(1, d.response_started_count());
1658 EXPECT_EQ(0, d.received_redirect_count());
1659}
1660
1661TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1662 // Intercept the main request to simulate a network error.
1663 interceptor()->set_simulate_main_network_error(true);
1664
1665 // Intercept that error and respond with an OK response.
1666 interceptor()->set_intercept_final_response(true);
1667 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1668 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1669
1670 TestDelegate d;
1671 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361672 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501673 req->set_method("GET");
1674 req->Start();
1675 base::RunLoop().Run();
1676
1677 // Check that the interceptor got called as expected.
1678 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1679 EXPECT_TRUE(interceptor()->did_intercept_final());
1680
1681 // Check that we received one good response.
1682 EXPECT_TRUE(req->status().is_success());
1683 EXPECT_EQ(200, req->response_headers()->response_code());
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, InterceptRestartRequired) {
1690 // Restart the main request.
1691 interceptor()->set_restart_main_request(true);
1692
1693 // then intercept the new main request and respond with an OK response
1694 interceptor()->set_intercept_main_request(true);
1695 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1696 interceptor()->set_main_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_restart_main());
1707 EXPECT_TRUE(interceptor()->did_intercept_main());
1708
1709 // Check that we received one good response.
1710 EXPECT_TRUE(req->status().is_success());
1711 if (req->status().is_success())
1712 EXPECT_EQ(200, req->response_headers()->response_code());
1713
1714 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1715 EXPECT_EQ(1, d.response_started_count());
1716 EXPECT_EQ(0, d.received_redirect_count());
1717}
1718
1719TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1720 // Intercept the main request and cancel from within the restarted job.
1721 interceptor()->set_cancel_main_request(true);
1722
1723 // Set up to intercept the final response and override it with an OK response.
1724 interceptor()->set_intercept_final_response(true);
1725 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1726 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1727
1728 TestDelegate d;
1729 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361730 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501731 req->set_method("GET");
1732 req->Start();
1733 base::RunLoop().Run();
1734
1735 // Check that the interceptor got called as expected.
1736 EXPECT_TRUE(interceptor()->did_cancel_main());
1737 EXPECT_FALSE(interceptor()->did_intercept_final());
1738
1739 // Check that we see a canceled request.
1740 EXPECT_FALSE(req->status().is_success());
1741 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1742}
1743
1744TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1745 // Intercept the main request and respond with a redirect.
1746 interceptor()->set_intercept_main_request(true);
1747 interceptor()->set_main_headers(
1748 MockURLRequestInterceptor::redirect_headers());
1749 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1750
1751 // Intercept the redirect and cancel from within that job.
1752 interceptor()->set_cancel_redirect_request(true);
1753
1754 // Set up to intercept the final response and override it with an OK response.
1755 interceptor()->set_intercept_final_response(true);
1756 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1757 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1758
1759 TestDelegate d;
1760 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361761 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501762 req->set_method("GET");
1763 req->Start();
1764 base::RunLoop().Run();
1765
1766 // Check that the interceptor got called as expected.
1767 EXPECT_TRUE(interceptor()->did_intercept_main());
1768 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1769 EXPECT_FALSE(interceptor()->did_intercept_final());
1770
1771 // Check that we see a canceled request.
1772 EXPECT_FALSE(req->status().is_success());
1773 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1774}
1775
1776TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1777 // Intercept the main request to simulate a network error.
1778 interceptor()->set_simulate_main_network_error(true);
1779
1780 // Set up to intercept final the response and cancel from within that job.
1781 interceptor()->set_cancel_final_request(true);
1782
1783 TestDelegate d;
1784 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361785 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501786 req->set_method("GET");
1787 req->Start();
1788 base::RunLoop().Run();
1789
1790 // Check that the interceptor got called as expected.
1791 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1792 EXPECT_TRUE(interceptor()->did_cancel_final());
1793
1794 // Check that we see a canceled request.
1795 EXPECT_FALSE(req->status().is_success());
1796 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1797}
1798
1799TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1800 // Intercept the main request and cancel then restart from within that job.
1801 interceptor()->set_cancel_then_restart_main_request(true);
1802
1803 // Set up to intercept the final response and override it with an OK response.
1804 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501805 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1806 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501807
1808 TestDelegate d;
1809 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361810 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501811 req->set_method("GET");
1812 req->Start();
1813 base::RunLoop().Run();
1814
1815 // Check that the interceptor got called as expected.
1816 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1817 EXPECT_FALSE(interceptor()->did_intercept_final());
1818
1819 // Check that we see a canceled request.
1820 EXPECT_FALSE(req->status().is_success());
1821 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591822}
1823
1824// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1825// reused. |connect_time_flags| is used to indicate if there should be dns
1826// or SSL times, and |used_proxy| is used for proxy times.
1827LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1828 int connect_time_flags,
1829 bool used_proxy) {
1830 LoadTimingInfo load_timing;
1831 load_timing.socket_log_id = 1;
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 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1839 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1840 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1841 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1842 }
1843 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1844 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1845 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1846 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1847 }
1848 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1849
1850 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1851 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1852 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1853 return load_timing;
1854}
1855
1856// Same as above, but in the case of a reused socket.
1857LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1858 bool used_proxy) {
1859 LoadTimingInfo load_timing;
1860 load_timing.socket_log_id = 1;
1861 load_timing.socket_reused = true;
1862
1863 if (used_proxy) {
1864 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1865 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1866 }
1867
1868 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1869 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1870 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1871 return load_timing;
1872}
1873
bengr1bf8e942014-11-07 01:36:501874LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1875 const LoadTimingInfo& job_load_timing,
1876 const URLRequestContext& context,
1877 MockURLRequestInterceptor* interceptor) {
1878 interceptor->set_intercept_main_request(true);
1879 interceptor->set_main_request_load_timing_info(job_load_timing);
1880 TestDelegate d;
1881 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361882 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501883 req->Start();
1884 base::RunLoop().Run();
1885
1886 LoadTimingInfo resulting_load_timing;
1887 req->GetLoadTimingInfo(&resulting_load_timing);
1888
1889 // None of these should be modified by the URLRequest.
1890 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1891 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1892 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1893 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1894 EXPECT_EQ(job_load_timing.receive_headers_end,
1895 resulting_load_timing.receive_headers_end);
1896
1897 return resulting_load_timing;
1898}
1899
[email protected]2bba3252013-04-08 19:50:591900// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501901TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591902 base::TimeTicks now = base::TimeTicks::Now();
1903 LoadTimingInfo job_load_timing =
1904 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1905
[email protected]2ca01e52013-10-31 22:05:191906 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501907 RunURLRequestInterceptorLoadTimingTest(
1908 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591909
1910 // Nothing should have been changed by the URLRequest.
1911 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1912 load_timing_result.proxy_resolve_start);
1913 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1914 load_timing_result.proxy_resolve_end);
1915 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1916 load_timing_result.connect_timing.dns_start);
1917 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1918 load_timing_result.connect_timing.dns_end);
1919 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1920 load_timing_result.connect_timing.connect_start);
1921 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1922 load_timing_result.connect_timing.connect_end);
1923 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1924 load_timing_result.connect_timing.ssl_start);
1925 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1926 load_timing_result.connect_timing.ssl_end);
1927
1928 // Redundant sanity check.
1929 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1930}
1931
1932// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501933TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591934 base::TimeTicks now = base::TimeTicks::Now();
1935 LoadTimingInfo job_load_timing =
1936 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1937
[email protected]2ca01e52013-10-31 22:05:191938 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501939 RunURLRequestInterceptorLoadTimingTest(
1940 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591941
1942 // Nothing should have been changed by the URLRequest.
1943 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1944 load_timing_result.proxy_resolve_start);
1945 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1946 load_timing_result.proxy_resolve_end);
1947 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1948 load_timing_result.connect_timing.dns_start);
1949 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1950 load_timing_result.connect_timing.dns_end);
1951 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1952 load_timing_result.connect_timing.connect_start);
1953 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1954 load_timing_result.connect_timing.connect_end);
1955 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1956 load_timing_result.connect_timing.ssl_start);
1957 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1958 load_timing_result.connect_timing.ssl_end);
1959
1960 // Redundant sanity check.
1961 TestLoadTimingNotReusedWithProxy(load_timing_result,
1962 CONNECT_TIMING_HAS_SSL_TIMES);
1963}
1964
1965// Make sure that URLRequest correctly adjusts proxy times when they're before
1966// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101967// the case of reusing a SPDY session. The connected socket is not considered
1968// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591969//
1970// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501971TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591972 base::TimeTicks now = base::TimeTicks::Now();
1973 LoadTimingInfo job_load_timing =
1974 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1975 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1976 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1977 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1978 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1979 job_load_timing.connect_timing.connect_start =
1980 now - base::TimeDelta::FromDays(2);
1981 job_load_timing.connect_timing.connect_end =
1982 now - base::TimeDelta::FromDays(1);
1983
[email protected]2ca01e52013-10-31 22:05:191984 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501985 RunURLRequestInterceptorLoadTimingTest(
1986 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591987
1988 // Proxy times, connect times, and DNS times should all be replaced with
1989 // request_start.
1990 EXPECT_EQ(load_timing_result.request_start,
1991 load_timing_result.proxy_resolve_start);
1992 EXPECT_EQ(load_timing_result.request_start,
1993 load_timing_result.proxy_resolve_end);
1994 EXPECT_EQ(load_timing_result.request_start,
1995 load_timing_result.connect_timing.dns_start);
1996 EXPECT_EQ(load_timing_result.request_start,
1997 load_timing_result.connect_timing.dns_end);
1998 EXPECT_EQ(load_timing_result.request_start,
1999 load_timing_result.connect_timing.connect_start);
2000 EXPECT_EQ(load_timing_result.request_start,
2001 load_timing_result.connect_timing.connect_end);
2002
2003 // Other times should have been left null.
2004 TestLoadTimingNotReusedWithProxy(load_timing_result,
2005 CONNECT_TIMING_HAS_DNS_TIMES);
2006}
2007
2008// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502009TEST_F(URLRequestInterceptorTest,
2010 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592011 base::TimeTicks now = base::TimeTicks::Now();
2012 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2013 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2014 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
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 // Proxy times and connect times should all be replaced with request_start.
2021 EXPECT_EQ(load_timing_result.request_start,
2022 load_timing_result.proxy_resolve_start);
2023 EXPECT_EQ(load_timing_result.request_start,
2024 load_timing_result.proxy_resolve_end);
2025
2026 // Other times should have been left null.
2027 TestLoadTimingReusedWithProxy(load_timing_result);
2028}
2029
2030// Make sure that URLRequest correctly adjusts connect times when they're before
2031// |request_start|, due to reusing a connected socket. The connected socket is
2032// not considered reused in this test (May be a preconnect).
2033//
2034// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502035TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592036 base::TimeTicks now = base::TimeTicks::Now();
2037 LoadTimingInfo job_load_timing =
2038 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2039 job_load_timing.connect_timing.connect_start =
2040 now - base::TimeDelta::FromDays(1);
2041 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2042 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2043 job_load_timing.connect_timing.connect_end =
2044 now - base::TimeDelta::FromDays(4);
2045
[email protected]2ca01e52013-10-31 22:05:192046 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502047 RunURLRequestInterceptorLoadTimingTest(
2048 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592049
2050 // Connect times, and SSL times should be replaced with request_start.
2051 EXPECT_EQ(load_timing_result.request_start,
2052 load_timing_result.connect_timing.connect_start);
2053 EXPECT_EQ(load_timing_result.request_start,
2054 load_timing_result.connect_timing.ssl_start);
2055 EXPECT_EQ(load_timing_result.request_start,
2056 load_timing_result.connect_timing.ssl_end);
2057 EXPECT_EQ(load_timing_result.request_start,
2058 load_timing_result.connect_timing.connect_end);
2059
2060 // Other times should have been left null.
2061 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2062}
2063
2064// Make sure that URLRequest correctly adjusts connect times when they're before
2065// |request_start|, due to reusing a connected socket in the case that there
2066// are also proxy times. The connected socket is not considered reused in this
2067// test (May be a preconnect).
2068//
2069// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502070TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592071 base::TimeTicks now = base::TimeTicks::Now();
2072 LoadTimingInfo job_load_timing =
2073 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2074 job_load_timing.connect_timing.connect_start =
2075 now - base::TimeDelta::FromDays(1);
2076 job_load_timing.connect_timing.connect_end =
2077 now - base::TimeDelta::FromDays(2);
2078
[email protected]2ca01e52013-10-31 22:05:192079 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502080 RunURLRequestInterceptorLoadTimingTest(
2081 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592082
2083 // Connect times should be replaced with proxy_resolve_end.
2084 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2085 load_timing_result.connect_timing.connect_start);
2086 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2087 load_timing_result.connect_timing.connect_end);
2088
2089 // Other times should have been left null.
2090 TestLoadTimingNotReusedWithProxy(load_timing_result,
2091 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2092}
2093
[email protected]316c1e5e2012-09-12 15:17:442094// Check that two different URL requests have different identifiers.
2095TEST_F(URLRequestTest, Identifiers) {
2096 TestDelegate d;
2097 TestURLRequestContext context;
davidben151423e2015-03-23 18:48:362098 scoped_ptr<URLRequest> req(
2099 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2100 scoped_ptr<URLRequest> other_req(
2101 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442102
mmenke19378d22014-09-09 04:12:592103 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442104}
2105
blundellb8163592f2015-12-16 14:22:422106#if defined(OS_IOS)
2107// TODO(droger): Check that a failure to connect to the proxy is reported to
2108// the network delegate. crbug.com/496743
2109#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2110#else
2111#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2112#endif
2113TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442114 MockHostResolver host_resolver;
2115 host_resolver.rules()->AddSimulatedFailure("*");
2116
[email protected]ceefd7fd2012-11-29 00:36:242117 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442118 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2119
2120 TestDelegate d;
davidben151423e2015-03-23 18:48:362121 scoped_ptr<URLRequest> req(
2122 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192123 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442124
[email protected]f7022f32014-08-21 16:32:192125 req->Start();
[email protected]255620da2013-08-19 13:14:292126 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442127
2128 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192129 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152130 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192131 EXPECT_TRUE(req->proxy_server().IsEmpty());
2132 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2133 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442134
2135 EXPECT_EQ(1, network_delegate.error_count());
2136 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2137 EXPECT_EQ(1, network_delegate.completed_requests());
2138}
2139
[email protected]cba24642014-08-15 20:49:592140// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442141// content is empty.
2142TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2143 TestDelegate d;
davidben151423e2015-03-23 18:48:362144 scoped_ptr<URLRequest> req(
2145 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192146 req->Start();
[email protected]255620da2013-08-19 13:14:292147 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442148 EXPECT_EQ("", d.data_received());
2149 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2150}
2151
[email protected]5033ab82013-03-22 20:17:462152// Make sure that SetPriority actually sets the URLRequest's priority
2153// correctly, both before and after start.
2154TEST_F(URLRequestTest, SetPriorityBasic) {
2155 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192156 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362157 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192158 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462159
[email protected]f7022f32014-08-21 16:32:192160 req->SetPriority(LOW);
2161 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462162
[email protected]f7022f32014-08-21 16:32:192163 req->Start();
2164 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462165
[email protected]f7022f32014-08-21 16:32:192166 req->SetPriority(MEDIUM);
2167 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462168}
2169
2170// Make sure that URLRequest calls SetPriority on a job before calling
2171// Start on it.
2172TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2173 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192174 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362175 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192176 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462177
mmenkeed0498b2015-12-08 23:20:422178 RequestPriority job_priority;
2179 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
2180 req.get(), &default_network_delegate_, &job_priority));
2181 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2182 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462183
[email protected]f7022f32014-08-21 16:32:192184 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462185
[email protected]f7022f32014-08-21 16:32:192186 req->Start();
mmenkeed0498b2015-12-08 23:20:422187 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462188}
2189
2190// Make sure that URLRequest passes on its priority updates to its
2191// job.
2192TEST_F(URLRequestTest, SetJobPriority) {
2193 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192194 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362195 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462196
mmenkeed0498b2015-12-08 23:20:422197 RequestPriority job_priority;
2198 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
2199 req.get(), &default_network_delegate_, &job_priority));
2200 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462201
[email protected]f7022f32014-08-21 16:32:192202 req->SetPriority(LOW);
2203 req->Start();
mmenkeed0498b2015-12-08 23:20:422204 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462205
[email protected]f7022f32014-08-21 16:32:192206 req->SetPriority(MEDIUM);
2207 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422208 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462209}
2210
[email protected]bb1c4662013-11-14 00:00:072211// Setting the IGNORE_LIMITS load flag should be okay if the priority
2212// is MAXIMUM_PRIORITY.
2213TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2214 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192215 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362216 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192217 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072218
mmenkeed0498b2015-12-08 23:20:422219 RequestPriority job_priority;
2220 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
2221 req.get(), &default_network_delegate_, &job_priority));
2222 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072223
[email protected]f7022f32014-08-21 16:32:192224 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2225 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072226
[email protected]f7022f32014-08-21 16:32:192227 req->SetPriority(MAXIMUM_PRIORITY);
2228 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072229
[email protected]f7022f32014-08-21 16:32:192230 req->Start();
2231 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422232 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072233}
2234
nick5d570de92015-05-04 20:16:162235namespace {
2236
2237// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552238class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442239 public:
tommycli59a63432015-11-06 00:10:552240 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2241 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272242 }
tommycli59a63432015-11-06 00:10:552243
2244 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2245};
tommyclieae5f75f2015-11-05 19:07:272246
nick5d570de92015-05-04 20:16:162247} // namespace
2248
[email protected]f2f31b32013-01-16 23:24:092249TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442250 LocalHttpTestServer test_server;
2251 ASSERT_TRUE(test_server.Start());
2252
2253 TestURLRequestContext context;
2254 scoped_refptr<DelayedCookieMonster> delayed_cm =
2255 new DelayedCookieMonster();
2256 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502257 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442258
2259 // Set up a cookie.
2260 {
2261 TestNetworkDelegate network_delegate;
2262 context.set_network_delegate(&network_delegate);
2263 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192264 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552265 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362266 &d));
[email protected]f7022f32014-08-21 16:32:192267 req->Start();
[email protected]255620da2013-08-19 13:14:292268 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442269 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2270 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2271 EXPECT_EQ(1, network_delegate.set_cookie_count());
2272 }
2273
2274 // Verify that the cookie is set.
2275 {
2276 TestNetworkDelegate network_delegate;
2277 context.set_network_delegate(&network_delegate);
2278 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192279 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552280 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192281 req->Start();
[email protected]255620da2013-08-19 13:14:292282 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442283
2284 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2285 != std::string::npos);
2286 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2287 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2288 }
2289}
2290
[email protected]f2f31b32013-01-16 23:24:092291TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442292 LocalHttpTestServer test_server;
2293 ASSERT_TRUE(test_server.Start());
2294
2295 // Set up a cookie.
2296 {
2297 TestNetworkDelegate network_delegate;
2298 default_context_.set_network_delegate(&network_delegate);
2299 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192300 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552301 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362302 &d));
[email protected]f7022f32014-08-21 16:32:192303 req->Start();
[email protected]255620da2013-08-19 13:14:292304 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442305 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2306 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2307 }
2308
2309 // Verify that the cookie is set.
2310 {
2311 TestNetworkDelegate network_delegate;
2312 default_context_.set_network_delegate(&network_delegate);
2313 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192314 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552315 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192316 req->Start();
[email protected]255620da2013-08-19 13:14:292317 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442318
2319 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2320 != std::string::npos);
2321 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2322 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2323 }
2324
2325 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2326 {
2327 TestNetworkDelegate network_delegate;
2328 default_context_.set_network_delegate(&network_delegate);
2329 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192330 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552331 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192332 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2333 req->Start();
[email protected]255620da2013-08-19 13:14:292334 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442335
2336 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2337 == std::string::npos);
2338
2339 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2340 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2341 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2342 }
2343}
2344
2345TEST_F(URLRequestTest, DoNotSaveCookies) {
2346 LocalHttpTestServer test_server;
2347 ASSERT_TRUE(test_server.Start());
2348
2349 // Set up a cookie.
2350 {
2351 TestNetworkDelegate network_delegate;
2352 default_context_.set_network_delegate(&network_delegate);
2353 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192354 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552355 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362356 &d));
[email protected]f7022f32014-08-21 16:32:192357 req->Start();
[email protected]255620da2013-08-19 13:14:292358 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442359
2360 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2361 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2362 EXPECT_EQ(1, network_delegate.set_cookie_count());
2363 }
2364
2365 // Try to set-up another cookie and update the previous cookie.
2366 {
2367 TestNetworkDelegate network_delegate;
2368 default_context_.set_network_delegate(&network_delegate);
2369 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192370 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552371 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362372 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192373 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2374 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442375
[email protected]255620da2013-08-19 13:14:292376 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442377
2378 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2379 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2380 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2381 EXPECT_EQ(0, network_delegate.set_cookie_count());
2382 }
2383
2384 // Verify the cookies weren't saved or updated.
2385 {
2386 TestNetworkDelegate network_delegate;
2387 default_context_.set_network_delegate(&network_delegate);
2388 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192389 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552390 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192391 req->Start();
[email protected]255620da2013-08-19 13:14:292392 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442393
2394 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2395 == std::string::npos);
2396 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
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 EXPECT_EQ(0, network_delegate.set_cookie_count());
2402 }
2403}
2404
2405TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2406 LocalHttpTestServer test_server;
2407 ASSERT_TRUE(test_server.Start());
2408
2409 // Set up a cookie.
2410 {
2411 TestNetworkDelegate network_delegate;
2412 default_context_.set_network_delegate(&network_delegate);
2413 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192414 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552415 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362416 &d));
[email protected]f7022f32014-08-21 16:32:192417 req->Start();
[email protected]255620da2013-08-19 13:14:292418 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442419
2420 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2421 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2422 }
2423
2424 // Verify that the cookie is set.
2425 {
2426 TestNetworkDelegate network_delegate;
2427 default_context_.set_network_delegate(&network_delegate);
2428 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192429 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552430 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192431 req->Start();
[email protected]255620da2013-08-19 13:14:292432 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442433
2434 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2435 != std::string::npos);
2436
2437 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2438 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2439 }
2440
2441 // Verify that the cookie isn't sent.
2442 {
2443 TestNetworkDelegate network_delegate;
2444 default_context_.set_network_delegate(&network_delegate);
2445 TestDelegate d;
2446 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192447 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552448 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192449 req->Start();
[email protected]255620da2013-08-19 13:14:292450 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442451
2452 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2453 == std::string::npos);
2454
[email protected]22e045f2013-09-20 03:54:032455 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442456 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2457 }
2458}
2459
marqf14fff8d2015-12-02 15:52:292460// TODO(crbug.com/564656) This test is flaky on iOS.
2461#if defined(OS_IOS)
2462#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2463#else
2464#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2465#endif
[email protected]316c1e5e2012-09-12 15:17:442466TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2467 LocalHttpTestServer test_server;
2468 ASSERT_TRUE(test_server.Start());
2469
2470 // Set up a cookie.
2471 {
2472 TestNetworkDelegate network_delegate;
2473 default_context_.set_network_delegate(&network_delegate);
2474 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192475 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552476 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362477 &d));
[email protected]f7022f32014-08-21 16:32:192478 req->Start();
[email protected]255620da2013-08-19 13:14:292479 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442480
2481 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2482 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2483 }
2484
2485 // Try to set-up another cookie and update the previous cookie.
2486 {
2487 TestNetworkDelegate network_delegate;
2488 default_context_.set_network_delegate(&network_delegate);
2489 TestDelegate d;
2490 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192491 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552492 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362493 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192494 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442495
[email protected]255620da2013-08-19 13:14:292496 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442497
2498 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2499 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2500 }
2501
2502 // Verify the cookies weren't saved or updated.
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("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192509 req->Start();
[email protected]255620da2013-08-19 13:14:292510 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442511
2512 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2513 == std::string::npos);
2514 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2515 != std::string::npos);
2516
2517 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2518 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2519 }
2520}
2521
2522TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2523 LocalHttpTestServer test_server;
2524 ASSERT_TRUE(test_server.Start());
2525
2526 // Set up an empty cookie.
2527 {
2528 TestNetworkDelegate network_delegate;
2529 default_context_.set_network_delegate(&network_delegate);
2530 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192531 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552532 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192533 req->Start();
[email protected]255620da2013-08-19 13:14:292534 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442535
2536 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2537 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2538 EXPECT_EQ(0, network_delegate.set_cookie_count());
2539 }
2540}
2541
2542TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2543 LocalHttpTestServer test_server;
2544 ASSERT_TRUE(test_server.Start());
2545
2546 // Set up a cookie.
2547 {
2548 TestNetworkDelegate network_delegate;
2549 default_context_.set_network_delegate(&network_delegate);
2550 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192551 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552552 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362553 &d));
[email protected]f7022f32014-08-21 16:32:192554 req->Start();
[email protected]255620da2013-08-19 13:14:292555 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442556
2557 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2558 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2559 }
2560
2561 // Verify that the cookie is set.
2562 {
2563 TestNetworkDelegate network_delegate;
2564 default_context_.set_network_delegate(&network_delegate);
2565 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192566 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552567 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192568 req->Start();
[email protected]255620da2013-08-19 13:14:292569 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442570
2571 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2572 != std::string::npos);
2573
2574 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2575 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2576 }
2577
2578 // Verify that the cookie isn't sent.
2579 {
2580 TestNetworkDelegate network_delegate;
2581 default_context_.set_network_delegate(&network_delegate);
2582 TestDelegate d;
2583 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192584 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552585 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192586 req->Start();
[email protected]255620da2013-08-19 13:14:292587 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442588
2589 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2590 == std::string::npos);
2591
[email protected]22e045f2013-09-20 03:54:032592 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442593 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2594 }
2595}
2596
2597TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2598 LocalHttpTestServer test_server;
2599 ASSERT_TRUE(test_server.Start());
2600
2601 // Set up a cookie.
2602 {
2603 TestNetworkDelegate network_delegate;
2604 default_context_.set_network_delegate(&network_delegate);
2605 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192606 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552607 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362608 &d));
[email protected]f7022f32014-08-21 16:32:192609 req->Start();
[email protected]255620da2013-08-19 13:14:292610 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442611
2612 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2613 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2614 }
2615
2616 // Try to set-up another cookie and update the previous cookie.
2617 {
2618 TestNetworkDelegate network_delegate;
2619 default_context_.set_network_delegate(&network_delegate);
2620 TestDelegate d;
2621 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192622 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552623 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362624 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192625 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442626
[email protected]255620da2013-08-19 13:14:292627 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442628
2629 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2630 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2631 }
2632
2633 // Verify the cookies weren't saved or updated.
2634 {
2635 TestNetworkDelegate network_delegate;
2636 default_context_.set_network_delegate(&network_delegate);
2637 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192638 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552639 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192640 req->Start();
[email protected]255620da2013-08-19 13:14:292641 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442642
2643 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2644 == std::string::npos);
2645 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2646 != std::string::npos);
2647
2648 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2649 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2650 }
2651}
2652
mkwst46549412016-02-01 10:05:372653TEST_F(URLRequestTest, SameSiteCookiesEnabled) {
mkwst3f3daac2015-02-26 20:15:262654 LocalHttpTestServer test_server;
2655 ASSERT_TRUE(test_server.Start());
2656
mkwst202534e32016-01-15 16:07:152657 TestNetworkDelegate network_delegate;
2658 network_delegate.set_experimental_cookie_features_enabled(true);
2659 default_context_.set_network_delegate(&network_delegate);
2660
mkwst46549412016-02-01 10:05:372661 // Set up a 'SameSite' cookie (on '127.0.0.1', as that's where
mkwst3f3daac2015-02-26 20:15:262662 // LocalHttpTestServer points).
2663 {
mkwst3f3daac2015-02-26 20:15:262664 TestDelegate d;
2665 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
mkwst46549412016-02-01 10:05:372666 test_server.GetURL("/set-cookie?SameSiteCookieToSet=1;SameSite"),
davidben151423e2015-03-23 18:48:362667 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262668 req->Start();
2669 base::RunLoop().Run();
2670 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2671 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2672 EXPECT_EQ(1, network_delegate.set_cookie_count());
2673 }
2674
mkwst46549412016-02-01 10:05:372675 // Verify that the cookie is sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262676 {
mkwst3f3daac2015-02-26 20:15:262677 TestDelegate d;
2678 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552679 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2680 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst202534e32016-01-15 16:07:152681 req->set_initiator(url::Origin(test_server.GetURL("/")));
mkwst3f3daac2015-02-26 20:15:262682 req->Start();
2683 base::RunLoop().Run();
2684
mkwst46549412016-02-01 10:05:372685 EXPECT_TRUE(d.data_received().find("SameSiteCookieToSet=1") !=
mkwst3f3daac2015-02-26 20:15:262686 std::string::npos);
2687 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2688 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2689 }
2690
mkwst46549412016-02-01 10:05:372691 // Verify that the cookie is not sent for cross-site requests.
mkwst3f3daac2015-02-26 20:15:262692 {
mkwst3f3daac2015-02-26 20:15:262693 TestDelegate d;
2694 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552695 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst46549412016-02-01 10:05:372696 req->set_first_party_for_cookies(GURL("http://cross-site.test/"));
2697 req->set_initiator(url::Origin(GURL("http://cross-site.test/")));
mkwst202534e32016-01-15 16:07:152698 req->Start();
2699 base::RunLoop().Run();
2700
mkwst46549412016-02-01 10:05:372701 EXPECT_TRUE(d.data_received().find("SameSiteCookieToSet=1") ==
mkwst202534e32016-01-15 16:07:152702 std::string::npos);
2703 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2704 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2705 }
2706
mkwst46549412016-02-01 10:05:372707 // Verify that the cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152708 // method is "safe".
2709 {
2710 TestDelegate d;
2711 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2712 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2713 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst46549412016-02-01 10:05:372714 req->set_initiator(url::Origin(GURL("http://cross-site.test/")));
mkwst202534e32016-01-15 16:07:152715 req->Start();
2716 base::RunLoop().Run();
2717
mkwst46549412016-02-01 10:05:372718 EXPECT_FALSE(d.data_received().find("SameSiteCookieToSet=1") ==
mkwst202534e32016-01-15 16:07:152719 std::string::npos);
2720 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2721 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2722 }
2723
mkwst46549412016-02-01 10:05:372724 // Verify that the cookie is not sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152725 // method is unsafe (e.g. POST).
2726 {
2727 TestDelegate d;
2728 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2729 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2730 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst46549412016-02-01 10:05:372731 req->set_initiator(url::Origin(GURL("http://cross-site.test/")));
mkwst202534e32016-01-15 16:07:152732 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:262733 req->Start();
2734 base::RunLoop().Run();
2735
mkwst46549412016-02-01 10:05:372736 EXPECT_TRUE(d.data_received().find("SameSiteCookieToSet=1") ==
mkwst3f3daac2015-02-26 20:15:262737 std::string::npos);
2738 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2739 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2740 }
2741}
2742
mkwst46549412016-02-01 10:05:372743TEST_F(URLRequestTest, SameSiteCookiesDisabled) {
mkwst0513c9d2015-04-01 05:53:152744 LocalHttpTestServer test_server;
2745 ASSERT_TRUE(test_server.Start());
2746
mkwst46549412016-02-01 10:05:372747 // Set up a 'SameSite' cookie (on '127.0.0.1', as that's where
mkwst0513c9d2015-04-01 05:53:152748 // LocalHttpTestServer points).
2749 {
2750 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412751 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152752 default_context_.set_network_delegate(&network_delegate);
2753
2754 TestDelegate d;
2755 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
mkwst46549412016-02-01 10:05:372756 test_server.GetURL("/set-cookie?SameSiteCookieToSet=1;SameSite"),
mkwst0513c9d2015-04-01 05:53:152757 DEFAULT_PRIORITY, &d));
2758 req->Start();
2759 base::RunLoop().Run();
2760 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2761 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2762 EXPECT_EQ(1, network_delegate.set_cookie_count());
2763 }
2764
mkwst46549412016-02-01 10:05:372765 // Verify that the cookie is sent for same-site requests.
mkwst0513c9d2015-04-01 05:53:152766 {
2767 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412768 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152769 default_context_.set_network_delegate(&network_delegate);
2770 TestDelegate d;
2771 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552772 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2773 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst0513c9d2015-04-01 05:53:152774 req->Start();
2775 base::RunLoop().Run();
2776
mkwst46549412016-02-01 10:05:372777 EXPECT_TRUE(d.data_received().find("SameSiteCookieToSet=1") !=
mkwst0513c9d2015-04-01 05:53:152778 std::string::npos);
2779 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2780 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2781 }
2782
mkwst46549412016-02-01 10:05:372783 // Verify that the cookie is also sent for cross-site requests.
mkwst0513c9d2015-04-01 05:53:152784 {
2785 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412786 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152787 default_context_.set_network_delegate(&network_delegate);
2788 TestDelegate d;
2789 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552790 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst46549412016-02-01 10:05:372791 req->set_first_party_for_cookies(GURL("http://cross-site.test/"));
mkwst0513c9d2015-04-01 05:53:152792 req->Start();
2793 base::RunLoop().Run();
2794
mkwst46549412016-02-01 10:05:372795 EXPECT_NE(d.data_received().find("SameSiteCookieToSet=1"),
jww79aceda2015-12-07 01:56:342796 std::string::npos);
mkwst0513c9d2015-04-01 05:53:152797 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2798 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2799 }
2800}
2801
estark557a5eb82015-12-01 22:57:102802// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:362803TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:552804 EmbeddedTestServer http_server;
2805 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362806 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552807 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2808 https_server.AddDefaultHandlers(
2809 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2810 ASSERT_TRUE(http_server.Start());
2811 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362812
estarkb15166b2015-12-18 16:56:382813 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362814 TestURLRequestContext context(true);
2815 context.set_network_delegate(&network_delegate);
2816 context.Init();
2817
estarkb15166b2015-12-18 16:56:382818 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362819 {
2820 TestDelegate d;
2821 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102822 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362823 DEFAULT_PRIORITY, &d));
2824 req->Start();
2825 base::RunLoop().Run();
2826 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2827 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2828 }
2829
2830 // Verify that the cookie is not set.
2831 {
2832 TestDelegate d;
2833 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552834 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362835 req->Start();
2836 base::RunLoop().Run();
2837
jww79aceda2015-12-07 01:56:342838 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
2839 std::string::npos);
estarkcd39c11f2015-10-19 19:46:362840 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2841 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2842 }
2843}
2844
estarkb15166b2015-12-18 16:56:382845TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:552846 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2847 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362848 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552849 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362850
2851 TestNetworkDelegate network_delegate;
2852 TestURLRequestContext context(true);
2853 context.set_network_delegate(&network_delegate);
2854 context.Init();
2855
estarkb15166b2015-12-18 16:56:382856 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362857 {
2858 TestDelegate d;
tommycli59a63432015-11-06 00:10:552859 scoped_ptr<URLRequest> req(
estark557a5eb82015-12-01 22:57:102860 context.CreateRequest(https_server.GetURL("/set-cookie?__Secure-foo=1"),
tommycli59a63432015-11-06 00:10:552861 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362862 req->Start();
2863 base::RunLoop().Run();
2864 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2865 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2866 }
2867
2868 // Verify that the cookie is not set.
2869 {
2870 TestDelegate d;
2871 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552872 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362873 req->Start();
2874 base::RunLoop().Run();
2875
jww79aceda2015-12-07 01:56:342876 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362877 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2878 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2879 }
2880}
2881
estarkb15166b2015-12-18 16:56:382882TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:552883 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2884 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362885 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552886 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362887
estarkb15166b2015-12-18 16:56:382888 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362889 TestURLRequestContext context(true);
2890 context.set_network_delegate(&network_delegate);
2891 context.Init();
2892
estarkb15166b2015-12-18 16:56:382893 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362894 {
2895 TestDelegate d;
2896 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102897 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
tommycli59a63432015-11-06 00:10:552898 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362899 req->Start();
2900 base::RunLoop().Run();
2901 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2902 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2903 }
2904
2905 // Verify that the cookie is set.
2906 {
2907 TestDelegate d;
2908 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552909 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362910 req->Start();
2911 base::RunLoop().Run();
2912
jww79aceda2015-12-07 01:56:342913 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
2914 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2915 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2916 }
2917}
2918
2919// Tests that secure cookies can't be set on non-secure origins if strict secure
2920// cookies are enabled.
2921TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
2922 EmbeddedTestServer http_server;
2923 http_server.AddDefaultHandlers(
2924 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2925 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2926 https_server.AddDefaultHandlers(
2927 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2928 ASSERT_TRUE(http_server.Start());
2929 ASSERT_TRUE(https_server.Start());
2930
2931 TestExperimentalFeaturesNetworkDelegate network_delegate;
2932 TestURLRequestContext context(true);
2933 context.set_network_delegate(&network_delegate);
2934 context.Init();
2935
2936 // Try to set a Secure cookie, with experimental features enabled.
2937 {
2938 TestDelegate d;
2939 scoped_ptr<URLRequest> req(context.CreateRequest(
2940 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
2941 DEFAULT_PRIORITY, &d));
2942 req->Start();
2943 base::RunLoop().Run();
2944 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2945 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2946 }
2947
2948 // Verify that the cookie is not set.
2949 {
2950 TestDelegate d;
2951 scoped_ptr<URLRequest> req(context.CreateRequest(
2952 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2953 req->Start();
2954 base::RunLoop().Run();
2955
2956 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
2957 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2958 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2959 }
2960}
2961
2962// Tests that secure cookies can be set on secure origins even if strict secure
2963// cookies are enabled.
2964TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
2965 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2966 https_server.AddDefaultHandlers(
2967 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2968 ASSERT_TRUE(https_server.Start());
2969
2970 TestExperimentalFeaturesNetworkDelegate network_delegate;
2971 TestURLRequestContext context(true);
2972 context.set_network_delegate(&network_delegate);
2973 context.Init();
2974
2975 // Try to set a Secure cookie, with experimental features enabled.
2976 {
2977 TestDelegate d;
2978 scoped_ptr<URLRequest> req(context.CreateRequest(
2979 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
2980 DEFAULT_PRIORITY, &d));
2981 req->Start();
2982 base::RunLoop().Run();
2983 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2984 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2985 }
2986
2987 // Verify that the cookie is not set.
2988 {
2989 TestDelegate d;
2990 scoped_ptr<URLRequest> req(context.CreateRequest(
2991 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2992 req->Start();
2993 base::RunLoop().Run();
2994
2995 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362996 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2997 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2998 }
2999}
3000
mmenkefb18c772015-09-30 22:22:503001// Tests that a request is cancelled while entering suspend mode. Uses mocks
3002// rather than a spawned test server because the connection used to talk to
3003// the test server is affected by entering suspend mode on Android.
3004TEST_F(URLRequestTest, CancelOnSuspend) {
3005 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
3006 base::PowerMonitor power_monitor(make_scoped_ptr(power_monitor_source));
3007
3008 URLRequestFailedJob::AddUrlHandler();
3009
3010 TestDelegate d;
3011 // Request that just hangs.
3012 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
3013 scoped_ptr<URLRequest> r(
3014 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
3015 r->Start();
3016
3017 power_monitor_source->Suspend();
3018 // Wait for the suspend notification to cause the request to fail.
3019 base::RunLoop().Run();
3020 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3021 EXPECT_TRUE(d.request_failed());
3022 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3023
3024 URLRequestFilter::GetInstance()->ClearHandlers();
3025
3026 // Shouldn't be needed, but just in case.
3027 power_monitor_source->Resume();
3028}
3029
[email protected]5095cd72012-11-01 10:29:163030// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3031// value for the |fixed_date| argument given to the constructor.
3032class FixedDateNetworkDelegate : public TestNetworkDelegate {
3033 public:
3034 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3035 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:203036 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163037
[email protected]cba24642014-08-15 20:49:593038 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203039 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593040 URLRequest* request,
3041 const CompletionCallback& callback,
3042 const HttpResponseHeaders* original_response_headers,
3043 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133044 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163045
3046 private:
3047 std::string fixed_date_;
3048
3049 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3050};
3051
3052int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593053 URLRequest* request,
3054 const CompletionCallback& callback,
3055 const HttpResponseHeaders* original_response_headers,
3056 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163057 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593058 HttpResponseHeaders* new_response_headers =
3059 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163060
3061 new_response_headers->RemoveHeader("Date");
3062 new_response_headers->AddHeader("Date: " + fixed_date_);
3063
3064 *override_response_headers = new_response_headers;
3065 return TestNetworkDelegate::OnHeadersReceived(request,
3066 callback,
3067 original_response_headers,
[email protected]5f714132014-03-26 10:41:163068 override_response_headers,
3069 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163070}
3071
3072// Test that cookie expiration times are adjusted for server/client clock
3073// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3074// headers by defaulting to GMT. (crbug.com/135131)
3075TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3076 LocalHttpTestServer test_server;
3077 ASSERT_TRUE(test_server.Start());
3078
3079 // Set up an expired cookie.
3080 {
3081 TestNetworkDelegate network_delegate;
3082 default_context_.set_network_delegate(&network_delegate);
3083 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193084 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193085 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553086 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363087 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193088 req->Start();
[email protected]255620da2013-08-19 13:14:293089 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163090 }
3091 // Verify that the cookie is not set.
3092 {
3093 TestNetworkDelegate network_delegate;
3094 default_context_.set_network_delegate(&network_delegate);
3095 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193096 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553097 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193098 req->Start();
[email protected]255620da2013-08-19 13:14:293099 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163100
3101 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3102 }
3103 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3104 {
3105 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3106 default_context_.set_network_delegate(&network_delegate);
3107 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193108 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193109 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553110 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363111 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193112 req->Start();
[email protected]255620da2013-08-19 13:14:293113 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163114 }
3115 // Verify that the cookie is set.
3116 {
3117 TestNetworkDelegate network_delegate;
3118 default_context_.set_network_delegate(&network_delegate);
3119 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193120 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553121 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193122 req->Start();
[email protected]255620da2013-08-19 13:14:293123 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163124
3125 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3126 }
3127}
3128
3129
[email protected]316c1e5e2012-09-12 15:17:443130// Check that it is impossible to change the referrer in the extra headers of
3131// an URLRequest.
3132TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3133 LocalHttpTestServer test_server;
3134 ASSERT_TRUE(test_server.Start());
3135
3136 // If extra headers contain referer and the request contains a referer,
3137 // only the latter shall be respected.
3138 {
3139 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193140 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553141 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193142 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443143
3144 HttpRequestHeaders headers;
3145 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193146 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443147
[email protected]f7022f32014-08-21 16:32:193148 req->Start();
[email protected]255620da2013-08-19 13:14:293149 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443150
3151 EXPECT_EQ("http://foo.com/", d.data_received());
3152 }
3153
3154 // If extra headers contain a referer but the request does not, no referer
3155 // shall be sent in the header.
3156 {
3157 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193158 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553159 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443160
3161 HttpRequestHeaders headers;
3162 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193163 req->SetExtraRequestHeaders(headers);
3164 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443165
[email protected]f7022f32014-08-21 16:32:193166 req->Start();
[email protected]255620da2013-08-19 13:14:293167 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443168
3169 EXPECT_EQ("None", d.data_received());
3170 }
3171}
3172
[email protected]b89290212009-08-14 22:37:353173class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113174 public:
mmenke9f2ec60c2015-06-01 20:59:473175 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113176
[email protected]b89290212009-08-14 22:37:353177 protected:
[email protected]21184962011-10-26 00:50:303178 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3179 // |request_method| is the method to use for the initial request.
3180 // |redirect_method| is the method that is expected to be used for the second
3181 // request, after redirection.
3182 // If |include_data| is true, data is uploaded with the request. The
3183 // response body is expected to match it exactly, if and only if
3184 // |request_method| == |redirect_method|.
3185 void HTTPRedirectMethodTest(const GURL& redirect_url,
3186 const std::string& request_method,
3187 const std::string& redirect_method,
3188 bool include_data) {
3189 static const char kData[] = "hello world";
3190 TestDelegate d;
davidben151423e2015-03-23 18:48:363191 scoped_ptr<URLRequest> req(
3192 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193193 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303194 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073195 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303196 HttpRequestHeaders headers;
3197 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513198 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543199 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193200 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303201 }
[email protected]f7022f32014-08-21 16:32:193202 req->Start();
[email protected]255620da2013-08-19 13:14:293203 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193204 EXPECT_EQ(redirect_method, req->method());
3205 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
3206 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:303207 if (include_data) {
3208 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543209 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3210 HttpRequestHeaders::kContentLength));
3211 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3212 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303213 EXPECT_EQ(kData, d.data_received());
3214 } else {
svaldez5b3a8972015-10-09 23:23:543215 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3216 HttpRequestHeaders::kContentLength));
3217 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3218 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303219 EXPECT_NE(kData, d.data_received());
3220 }
3221 }
3222 if (HasFailure())
3223 LOG(WARNING) << "Request method was: " << request_method;
3224 }
3225
jww5fe460ff2015-03-28 00:22:513226 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3227 // |request_method| is the method to use for the initial request.
3228 // |redirect_method| is the method that is expected to be used for the second
3229 // request, after redirection.
3230 // |origin_value| is the expected value for the Origin header after
3231 // redirection. If empty, expects that there will be no Origin header.
3232 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3233 const std::string& request_method,
3234 const std::string& redirect_method,
3235 const std::string& origin_value) {
3236 TestDelegate d;
3237 scoped_ptr<URLRequest> req(
3238 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3239 req->set_method(request_method);
3240 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3241 redirect_url.GetOrigin().spec(), false);
3242 req->Start();
3243
3244 base::RunLoop().Run();
3245
3246 EXPECT_EQ(redirect_method, req->method());
3247 // Note that there is no check for request success here because, for
3248 // purposes of testing, the request very well may fail. For example, if the
3249 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3250 // origin, there is not an HTTPS server in this unit test framework, so the
3251 // request would fail. However, that's fine, as long as the request headers
3252 // are in order and pass the checks below.
3253 if (origin_value.empty()) {
3254 EXPECT_FALSE(
3255 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3256 } else {
3257 std::string origin_header;
3258 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3259 HttpRequestHeaders::kOrigin, &origin_header));
3260 EXPECT_EQ(origin_value, origin_header);
3261 }
3262 }
3263
[email protected]762d2db2010-01-11 19:03:013264 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013265 const int kMsgSize = 20000; // multiple of 10
3266 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483267 char* uploadBytes = new char[kMsgSize+1];
3268 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013269 char marker = 'a';
3270 for (int idx = 0; idx < kMsgSize/10; idx++) {
3271 memcpy(ptr, "----------", 10);
3272 ptr += 10;
3273 if (idx % 100 == 0) {
3274 ptr--;
3275 *ptr++ = marker;
3276 if (++marker > 'z')
3277 marker = 'a';
3278 }
3279 }
3280 uploadBytes[kMsgSize] = '\0';
3281
[email protected]762d2db2010-01-11 19:03:013282 for (int i = 0; i < kIterations; ++i) {
3283 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193284 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553285 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193286 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013287
mmenkecbc2b712014-10-09 20:29:073288 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013289
[email protected]f7022f32014-08-21 16:32:193290 r->Start();
3291 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013292
[email protected]255620da2013-08-19 13:14:293293 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013294
[email protected]329b68b2012-11-14 17:54:273295 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:193296 << "request failed: " << r->status().status()
3297 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:013298
3299 EXPECT_FALSE(d.received_data_before_response());
3300 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013301 }
3302 delete[] uploadBytes;
3303 }
3304
[email protected]ef2bf422012-05-11 03:27:093305 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:223306 r->AppendChunkToUpload("a", 1, false);
3307 r->AppendChunkToUpload("bcd", 3, false);
3308 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
3309 r->AppendChunkToUpload("\r\n\r\n", 4, false);
3310 r->AppendChunkToUpload("0", 1, false);
3311 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:113312 }
3313
[email protected]ef2bf422012-05-11 03:27:093314 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:113315 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:273316 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:113317 "abcdthis is a longer chunk than before.\r\n\r\n02323";
3318
[email protected]329b68b2012-11-14 17:54:273319 ASSERT_EQ(1, d->response_started_count())
3320 << "request failed: " << r->status().status()
3321 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:113322
3323 EXPECT_FALSE(d->received_data_before_response());
3324
[email protected]329b68b2012-11-14 17:54:273325 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
3326 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:113327 }
3328
[email protected]ede03212012-09-07 12:52:263329 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343330 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193331 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553332 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363333 base::IntToString(num_cookies)),
3334 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343335
[email protected]f7022f32014-08-21 16:32:193336 r->Start();
3337 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343338
[email protected]255620da2013-08-19 13:14:293339 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343340
[email protected]f7022f32014-08-21 16:32:193341 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:343342
tommycli59a63432015-11-06 00:10:553343 if (!is_success)
[email protected]f7022f32014-08-21 16:32:193344 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:343345
3346 return is_success;
3347 }
3348
tommycli59a63432015-11-06 00:10:553349 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503350
tommycli59a63432015-11-06 00:10:553351 private:
[email protected]1700c6a2012-02-22 18:07:073352 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353353};
3354
tommycli59a63432015-11-06 00:10:553355namespace {
3356
3357scoped_ptr<test_server::HttpResponse> HandleRedirectConnect(
3358 const test_server::HttpRequest& request) {
3359 if (request.headers.find("Host") == request.headers.end() ||
3360 request.headers.at("Host") != "www.redirect.com" ||
3361 request.method != test_server::METHOD_CONNECT) {
3362 return nullptr;
3363 }
3364
3365 scoped_ptr<test_server::BasicHttpResponse> http_response(
3366 new test_server::BasicHttpResponse);
3367 http_response->set_code(HTTP_FOUND);
3368 http_response->AddCustomHeader("Location",
3369 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:483370 return std::move(http_response);
tommycli59a63432015-11-06 00:10:553371}
3372
3373} // namespace
3374
nharperb7441ef2016-01-25 23:54:143375class TestSSLConfigService : public SSLConfigService {
3376 public:
3377 TestSSLConfigService(bool ev_enabled,
3378 bool online_rev_checking,
3379 bool rev_checking_required_local_anchors,
3380 bool token_binding_enabled)
3381 : ev_enabled_(ev_enabled),
3382 online_rev_checking_(online_rev_checking),
3383 rev_checking_required_local_anchors_(
3384 rev_checking_required_local_anchors),
3385 token_binding_enabled_(token_binding_enabled),
3386 min_version_(kDefaultSSLVersionMin),
3387 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
3388
3389 void set_min_version(uint16_t version) { min_version_ = version; }
3390
3391 void set_fallback_min_version(uint16_t version) {
3392 fallback_min_version_ = version;
3393 }
3394
3395 // SSLConfigService:
3396 void GetSSLConfig(SSLConfig* config) override {
3397 *config = SSLConfig();
3398 config->rev_checking_enabled = online_rev_checking_;
3399 config->verify_ev_cert = ev_enabled_;
3400 config->rev_checking_required_local_anchors =
3401 rev_checking_required_local_anchors_;
3402 if (fallback_min_version_) {
3403 config->version_fallback_min = fallback_min_version_;
3404 }
3405 if (min_version_) {
3406 config->version_min = min_version_;
3407 }
3408 if (token_binding_enabled_) {
3409 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
3410 }
3411 }
3412
3413 protected:
3414 ~TestSSLConfigService() override {}
3415
3416 private:
3417 const bool ev_enabled_;
3418 const bool online_rev_checking_;
3419 const bool rev_checking_required_local_anchors_;
3420 const bool token_binding_enabled_;
3421 uint16_t min_version_;
3422 uint16_t fallback_min_version_;
3423};
3424
3425// TODO(svaldez): Update tests to use EmbeddedTestServer.
3426#if !defined(OS_IOS)
3427class TokenBindingURLRequestTest : public URLRequestTestHTTP {
3428 public:
3429 void SetUp() override {
3430 default_context_.set_ssl_config_service(
3431 new TestSSLConfigService(false, false, false, true));
3432 channel_id_service_.reset(new ChannelIDService(
3433 new DefaultChannelIDStore(NULL), base::ThreadTaskRunnerHandle::Get()));
3434 default_context_.set_channel_id_service(channel_id_service_.get());
3435 URLRequestTestHTTP::SetUp();
3436 }
3437
3438 protected:
3439 scoped_ptr<ChannelIDService> channel_id_service_;
3440};
3441
3442TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
3443 SpawnedTestServer::SSLOptions ssl_options;
3444 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3445 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3446 ssl_options,
3447 base::FilePath(kTestFilePath));
3448 ASSERT_TRUE(https_test_server.Start());
3449
3450 TestDelegate d;
3451 {
3452 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3453 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d));
3454 r->Start();
3455 EXPECT_TRUE(r->is_pending());
3456
3457 base::RunLoop().Run();
3458
3459 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3460
3461 HttpRequestHeaders headers;
3462 std::string token_binding_header, token_binding_message;
3463 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3464 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3465 &token_binding_header));
3466 EXPECT_TRUE(base::Base64UrlDecode(
3467 token_binding_header, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
3468 &token_binding_message));
3469 base::StringPiece ec_point, signature;
3470 EXPECT_TRUE(
3471 ParseTokenBindingMessage(token_binding_message, &ec_point, &signature));
3472
3473 EXPECT_GT(d.bytes_received(), 0);
3474 std::string ekm = d.data_received();
3475
3476 EXPECT_TRUE(VerifyEKMSignature(ec_point, signature, ekm));
3477 }
3478}
3479#endif // !defined(OS_IOS)
3480
3481// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113482// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553483// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113484// follow.
[email protected]f2f31b32013-01-16 23:24:093485TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553486 http_test_server()->RegisterRequestHandler(
3487 base::Bind(&HandleRedirectConnect));
3488 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113489
[email protected]ceefd7fd2012-11-29 00:36:243490 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043491 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553492 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503493
[email protected]d1ec59082009-02-11 02:48:153494 TestDelegate d;
3495 {
[email protected]f7022f32014-08-21 16:32:193496 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363497 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193498 r->Start();
3499 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153500
[email protected]255620da2013-08-19 13:14:293501 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153502
[email protected]f7022f32014-08-21 16:32:193503 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153504 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193505 EXPECT_TRUE(r->proxy_server().IsEmpty());
3506 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083507 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153508 // We should not have followed the redirect.
3509 EXPECT_EQ(0, d.received_redirect_count());
3510 }
3511}
3512
[email protected]8202d0c2011-02-23 08:31:143513// This is the same as the previous test, but checks that the network delegate
3514// registers the error.
[email protected]c044616e2013-02-20 02:01:263515TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553516 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143517
[email protected]ceefd7fd2012-11-29 00:36:243518 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043519 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553520 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503521
[email protected]8202d0c2011-02-23 08:31:143522 TestDelegate d;
3523 {
[email protected]f7022f32014-08-21 16:32:193524 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363525 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193526 r->Start();
3527 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143528
[email protected]255620da2013-08-19 13:14:293529 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143530
[email protected]f7022f32014-08-21 16:32:193531 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153532 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193533 EXPECT_TRUE(r->proxy_server().IsEmpty());
3534 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143535 EXPECT_EQ(1, d.response_started_count());
3536 // We should not have followed the redirect.
3537 EXPECT_EQ(0, d.received_redirect_count());
3538
3539 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053540 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143541 }
3542}
3543
[email protected]dc5a5cf2012-09-26 02:49:303544// Tests that we can block and asynchronously return OK in various stages.
3545TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3546 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3547 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3548 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3549 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3550 };
3551 static const size_t blocking_stages_length = arraysize(blocking_stages);
3552
tommycli59a63432015-11-06 00:10:553553 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:303554
3555 TestDelegate d;
3556 BlockingNetworkDelegate network_delegate(
3557 BlockingNetworkDelegate::USER_CALLBACK);
3558 network_delegate.set_block_on(
3559 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3560 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3561 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3562
3563 TestURLRequestContext context(true);
3564 context.set_network_delegate(&network_delegate);
3565 context.Init();
3566
3567 {
[email protected]f7022f32014-08-21 16:32:193568 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553569 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303570
[email protected]f7022f32014-08-21 16:32:193571 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303572 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293573 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303574 EXPECT_EQ(blocking_stages[i],
3575 network_delegate.stage_blocked_for_callback());
3576 network_delegate.DoCallback(OK);
3577 }
[email protected]255620da2013-08-19 13:14:293578 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193579 EXPECT_EQ(200, r->GetResponseCode());
3580 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303581 EXPECT_EQ(1, network_delegate.created_requests());
3582 EXPECT_EQ(0, network_delegate.destroyed_requests());
3583 }
3584 EXPECT_EQ(1, network_delegate.destroyed_requests());
3585}
3586
[email protected]4c76d7c2011-04-15 19:14:123587// Tests that the network delegate can block and cancel a request.
3588TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:553589 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123590
3591 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303592 BlockingNetworkDelegate network_delegate(
3593 BlockingNetworkDelegate::AUTO_CALLBACK);
3594 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3595 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123596
[email protected]d5a4dd62012-05-23 01:41:043597 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553598 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503599
[email protected]4c76d7c2011-04-15 19:14:123600 {
[email protected]f7022f32014-08-21 16:32:193601 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553602 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123603
[email protected]f7022f32014-08-21 16:32:193604 r->Start();
[email protected]255620da2013-08-19 13:14:293605 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123606
[email protected]f7022f32014-08-21 16:32:193607 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153608 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193609 EXPECT_TRUE(r->proxy_server().IsEmpty());
3610 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123611 EXPECT_EQ(1, network_delegate.created_requests());
3612 EXPECT_EQ(0, network_delegate.destroyed_requests());
3613 }
3614 EXPECT_EQ(1, network_delegate.destroyed_requests());
3615}
3616
[email protected]b4438d32012-09-27 06:15:303617// Helper function for NetworkDelegateCancelRequestAsynchronously and
3618// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3619// delegate operating in |block_mode| and a request for |url|. It blocks the
3620// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3621void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3622 BlockingNetworkDelegate::Stage stage,
3623 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363624 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303625 BlockingNetworkDelegate network_delegate(block_mode);
3626 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3627 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363628
[email protected]b4438d32012-09-27 06:15:303629 TestURLRequestContext context(true);
3630 context.set_network_delegate(&network_delegate);
3631 context.Init();
[email protected]3cd384c602011-08-31 16:12:363632
3633 {
davidben151423e2015-03-23 18:48:363634 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363635
[email protected]f7022f32014-08-21 16:32:193636 r->Start();
[email protected]255620da2013-08-19 13:14:293637 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363638
[email protected]f7022f32014-08-21 16:32:193639 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153640 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193641 EXPECT_TRUE(r->proxy_server().IsEmpty());
3642 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363643 EXPECT_EQ(1, network_delegate.created_requests());
3644 EXPECT_EQ(0, network_delegate.destroyed_requests());
3645 }
3646 EXPECT_EQ(1, network_delegate.destroyed_requests());
3647}
3648
[email protected]b4438d32012-09-27 06:15:303649// The following 3 tests check that the network delegate can cancel a request
3650// synchronously in various stages of the request.
3651TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:553652 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303653 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3654 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553655 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303656}
3657
3658TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:553659 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303660 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3661 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553662 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303663}
3664
3665TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:553666 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303667 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3668 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553669 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303670}
3671
3672// The following 3 tests check that the network delegate can cancel a request
3673// asynchronously in various stages of the request.
3674TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:553675 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303676 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3677 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553678 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303679}
3680
3681TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:553682 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303683 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3684 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553685 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303686}
3687
3688TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:553689 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303690 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3691 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553692 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303693}
3694
[email protected]4c76d7c2011-04-15 19:14:123695// Tests that the network delegate can block and redirect a request to a new
3696// URL.
3697TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:553698 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123699
3700 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303701 BlockingNetworkDelegate network_delegate(
3702 BlockingNetworkDelegate::AUTO_CALLBACK);
3703 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553704 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:123705 network_delegate.set_redirect_url(redirect_url);
3706
[email protected]d5a4dd62012-05-23 01:41:043707 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553708 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503709
[email protected]4c76d7c2011-04-15 19:14:123710 {
tommycli59a63432015-11-06 00:10:553711 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363712 scoped_ptr<URLRequest> r(
3713 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123714
[email protected]6be6fa92014-08-06 23:44:563715 // Quit after hitting the redirect, so can check the headers.
3716 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193717 r->Start();
[email protected]255620da2013-08-19 13:14:293718 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123719
[email protected]6be6fa92014-08-06 23:44:563720 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193721 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3722 EXPECT_EQ(307, r->GetResponseCode());
3723 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563724 std::string location;
[email protected]f7022f32014-08-21 16:32:193725 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3726 &location));
[email protected]6be6fa92014-08-06 23:44:563727 EXPECT_EQ(redirect_url, GURL(location));
3728
3729 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193730 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563731 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193732 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553733 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273734 EXPECT_EQ(
3735 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553736 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3737 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273738
[email protected]f7022f32014-08-21 16:32:193739 EXPECT_EQ(0, r->status().error());
3740 EXPECT_EQ(redirect_url, r->url());
3741 EXPECT_EQ(original_url, r->original_url());
3742 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123743 EXPECT_EQ(1, network_delegate.created_requests());
3744 EXPECT_EQ(0, network_delegate.destroyed_requests());
3745 }
3746 EXPECT_EQ(1, network_delegate.destroyed_requests());
3747}
3748
[email protected]b813ed72012-04-05 08:21:363749// Tests that the network delegate can block and redirect a request to a new
3750// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3751TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:553752 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:363753
3754 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303755 BlockingNetworkDelegate network_delegate(
3756 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:553757 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:363758 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363759
[email protected]d5a4dd62012-05-23 01:41:043760 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553761 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363762
3763 {
tommycli59a63432015-11-06 00:10:553764 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363765 scoped_ptr<URLRequest> r(
3766 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363767
[email protected]6be6fa92014-08-06 23:44:563768 // Quit after hitting the redirect, so can check the headers.
3769 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193770 r->Start();
[email protected]255620da2013-08-19 13:14:293771 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363772
[email protected]6be6fa92014-08-06 23:44:563773 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193774 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3775 EXPECT_EQ(307, r->GetResponseCode());
3776 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563777 std::string location;
[email protected]f7022f32014-08-21 16:32:193778 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3779 &location));
[email protected]6be6fa92014-08-06 23:44:563780 EXPECT_EQ(redirect_url, GURL(location));
3781
3782 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193783 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563784 base::RunLoop().Run();
3785
[email protected]f7022f32014-08-21 16:32:193786 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553787 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273788 EXPECT_EQ(
3789 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553790 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3791 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193792 EXPECT_EQ(0, r->status().error());
3793 EXPECT_EQ(redirect_url, r->url());
3794 EXPECT_EQ(original_url, r->original_url());
3795 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363796 EXPECT_EQ(1, network_delegate.created_requests());
3797 EXPECT_EQ(0, network_delegate.destroyed_requests());
3798 }
3799 EXPECT_EQ(1, network_delegate.destroyed_requests());
3800}
3801
[email protected]3c5ca8c2011-09-29 01:14:513802// Tests that redirects caused by the network delegate preserve POST data.
3803TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:553804 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:513805
3806 const char kData[] = "hello world";
3807
3808 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303809 BlockingNetworkDelegate network_delegate(
3810 BlockingNetworkDelegate::AUTO_CALLBACK);
3811 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553812 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:513813 network_delegate.set_redirect_url(redirect_url);
3814
[email protected]ef2bf422012-05-11 03:27:093815 TestURLRequestContext context(true);
3816 context.set_network_delegate(&network_delegate);
3817 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513818
3819 {
tommycli59a63432015-11-06 00:10:553820 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363821 scoped_ptr<URLRequest> r(
3822 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193823 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073824 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513825 HttpRequestHeaders headers;
3826 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513827 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193828 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563829
3830 // Quit after hitting the redirect, so can check the headers.
3831 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193832 r->Start();
[email protected]255620da2013-08-19 13:14:293833 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513834
[email protected]6be6fa92014-08-06 23:44:563835 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193836 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3837 EXPECT_EQ(307, r->GetResponseCode());
3838 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563839 std::string location;
[email protected]f7022f32014-08-21 16:32:193840 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3841 &location));
[email protected]6be6fa92014-08-06 23:44:563842 EXPECT_EQ(redirect_url, GURL(location));
3843
3844 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193845 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563846 base::RunLoop().Run();
3847
[email protected]f7022f32014-08-21 16:32:193848 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3849 EXPECT_EQ(0, r->status().error());
3850 EXPECT_EQ(redirect_url, r->url());
3851 EXPECT_EQ(original_url, r->original_url());
3852 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513853 EXPECT_EQ(1, network_delegate.created_requests());
3854 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193855 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513856 EXPECT_EQ(kData, d.data_received());
3857 }
3858 EXPECT_EQ(1, network_delegate.destroyed_requests());
3859}
3860
[email protected]5f714132014-03-26 10:41:163861// Tests that the network delegate can block and redirect a request to a new
3862// URL during OnHeadersReceived.
3863TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:553864 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:163865
3866 TestDelegate d;
3867 BlockingNetworkDelegate network_delegate(
3868 BlockingNetworkDelegate::AUTO_CALLBACK);
3869 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:553870 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:163871 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3872
3873 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553874 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:163875
3876 {
tommycli59a63432015-11-06 00:10:553877 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363878 scoped_ptr<URLRequest> r(
3879 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163880
[email protected]f7022f32014-08-21 16:32:193881 r->Start();
[email protected]5f714132014-03-26 10:41:163882 base::RunLoop().Run();
3883
[email protected]f7022f32014-08-21 16:32:193884 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553885 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273886 EXPECT_EQ(
3887 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553888 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3889 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193890
3891 EXPECT_EQ(OK, r->status().error());
3892 EXPECT_EQ(redirect_url, r->url());
3893 EXPECT_EQ(original_url, r->original_url());
3894 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163895 EXPECT_EQ(2, network_delegate.created_requests());
3896 EXPECT_EQ(0, network_delegate.destroyed_requests());
3897 }
3898 EXPECT_EQ(1, network_delegate.destroyed_requests());
3899}
3900
[email protected]c2911d72011-10-03 22:16:363901// Tests that the network delegate can synchronously complete OnAuthRequired
3902// by taking no action. This indicates that the NetworkDelegate does not want to
3903// handle the challenge, and is passing the buck along to the
3904// URLRequest::Delegate.
3905TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:553906 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363907
3908 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303909 BlockingNetworkDelegate network_delegate(
3910 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363911
[email protected]ef2bf422012-05-11 03:27:093912 TestURLRequestContext context(true);
3913 context.set_network_delegate(&network_delegate);
3914 context.Init();
[email protected]c2911d72011-10-03 22:16:363915
[email protected]f3cf9802011-10-28 18:44:583916 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363917
3918 {
tommycli59a63432015-11-06 00:10:553919 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363920 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193921 r->Start();
[email protected]79e1fd62013-06-20 06:50:043922
[email protected]255620da2013-08-19 13:14:293923 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043924
[email protected]f7022f32014-08-21 16:32:193925 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3926 EXPECT_EQ(0, r->status().error());
3927 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043928 EXPECT_TRUE(d.auth_required_called());
3929 EXPECT_EQ(1, network_delegate.created_requests());
3930 EXPECT_EQ(0, network_delegate.destroyed_requests());
3931 }
3932 EXPECT_EQ(1, network_delegate.destroyed_requests());
3933}
3934
3935TEST_F(URLRequestTestHTTP,
3936 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:553937 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:043938
3939 TestDelegate d;
3940 BlockingNetworkDelegate network_delegate(
3941 BlockingNetworkDelegate::SYNCHRONOUS);
3942
3943 TestURLRequestContext context(true);
3944 context.set_network_delegate(&network_delegate);
3945 context.Init();
3946
3947 d.set_credentials(AuthCredentials(kUser, kSecret));
3948
3949 {
tommycli59a63432015-11-06 00:10:553950 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363951 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193952 r->Start();
[email protected]79e1fd62013-06-20 06:50:043953
3954 {
3955 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193956 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043957 EXPECT_FALSE(headers.HasHeader("Authorization"));
3958 }
3959
[email protected]255620da2013-08-19 13:14:293960 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363961
[email protected]f7022f32014-08-21 16:32:193962 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3963 EXPECT_EQ(0, r->status().error());
3964 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363965 EXPECT_TRUE(d.auth_required_called());
3966 EXPECT_EQ(1, network_delegate.created_requests());
3967 EXPECT_EQ(0, network_delegate.destroyed_requests());
3968 }
3969 EXPECT_EQ(1, network_delegate.destroyed_requests());
3970}
3971
3972// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403973// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363974TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:553975 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363976
3977 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303978 BlockingNetworkDelegate network_delegate(
3979 BlockingNetworkDelegate::SYNCHRONOUS);
3980 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363981 network_delegate.set_auth_retval(
3982 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3983
[email protected]f3cf9802011-10-28 18:44:583984 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363985
[email protected]ef2bf422012-05-11 03:27:093986 TestURLRequestContext context(true);
3987 context.set_network_delegate(&network_delegate);
3988 context.Init();
[email protected]c2911d72011-10-03 22:16:363989
3990 {
tommycli59a63432015-11-06 00:10:553991 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363992 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193993 r->Start();
[email protected]255620da2013-08-19 13:14:293994 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363995
[email protected]f7022f32014-08-21 16:32:193996 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3997 EXPECT_EQ(0, r->status().error());
3998 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363999 EXPECT_FALSE(d.auth_required_called());
4000 EXPECT_EQ(1, network_delegate.created_requests());
4001 EXPECT_EQ(0, network_delegate.destroyed_requests());
4002 }
4003 EXPECT_EQ(1, network_delegate.destroyed_requests());
4004}
4005
[email protected]79e1fd62013-06-20 06:50:044006// Same as above, but also tests that GetFullRequestHeaders returns the proper
4007// headers (for the first or second request) when called at the proper times.
4008TEST_F(URLRequestTestHTTP,
4009 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554010 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044011
4012 TestDelegate d;
4013 BlockingNetworkDelegate network_delegate(
4014 BlockingNetworkDelegate::SYNCHRONOUS);
4015 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4016 network_delegate.set_auth_retval(
4017 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4018
4019 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4020
4021 TestURLRequestContext context(true);
4022 context.set_network_delegate(&network_delegate);
4023 context.Init();
4024
4025 {
tommycli59a63432015-11-06 00:10:554026 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364027 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194028 r->Start();
[email protected]255620da2013-08-19 13:14:294029 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044030
[email protected]f7022f32014-08-21 16:32:194031 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4032 EXPECT_EQ(0, r->status().error());
4033 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044034 EXPECT_FALSE(d.auth_required_called());
4035 EXPECT_EQ(1, network_delegate.created_requests());
4036 EXPECT_EQ(0, network_delegate.destroyed_requests());
4037
4038 {
4039 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194040 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044041 EXPECT_TRUE(headers.HasHeader("Authorization"));
4042 }
4043 }
4044 EXPECT_EQ(1, network_delegate.destroyed_requests());
4045}
4046
[email protected]c2911d72011-10-03 22:16:364047// Tests that the network delegate can synchronously complete OnAuthRequired
4048// by cancelling authentication.
4049TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554050 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364051
4052 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304053 BlockingNetworkDelegate network_delegate(
4054 BlockingNetworkDelegate::SYNCHRONOUS);
4055 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364056 network_delegate.set_auth_retval(
4057 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4058
[email protected]ef2bf422012-05-11 03:27:094059 TestURLRequestContext context(true);
4060 context.set_network_delegate(&network_delegate);
4061 context.Init();
[email protected]c2911d72011-10-03 22:16:364062
4063 {
tommycli59a63432015-11-06 00:10:554064 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364065 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194066 r->Start();
[email protected]255620da2013-08-19 13:14:294067 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364068
[email protected]f7022f32014-08-21 16:32:194069 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4070 EXPECT_EQ(OK, r->status().error());
4071 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364072 EXPECT_FALSE(d.auth_required_called());
4073 EXPECT_EQ(1, network_delegate.created_requests());
4074 EXPECT_EQ(0, network_delegate.destroyed_requests());
4075 }
4076 EXPECT_EQ(1, network_delegate.destroyed_requests());
4077}
4078
4079// Tests that the network delegate can asynchronously complete OnAuthRequired
4080// by taking no action. This indicates that the NetworkDelegate does not want
4081// to handle the challenge, and is passing the buck along to the
4082// URLRequest::Delegate.
4083TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554084 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364085
4086 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304087 BlockingNetworkDelegate network_delegate(
4088 BlockingNetworkDelegate::AUTO_CALLBACK);
4089 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364090
[email protected]ef2bf422012-05-11 03:27:094091 TestURLRequestContext context(true);
4092 context.set_network_delegate(&network_delegate);
4093 context.Init();
[email protected]c2911d72011-10-03 22:16:364094
[email protected]f3cf9802011-10-28 18:44:584095 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364096
4097 {
tommycli59a63432015-11-06 00:10:554098 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364099 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194100 r->Start();
[email protected]255620da2013-08-19 13:14:294101 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364102
[email protected]f7022f32014-08-21 16:32:194103 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4104 EXPECT_EQ(0, r->status().error());
4105 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364106 EXPECT_TRUE(d.auth_required_called());
4107 EXPECT_EQ(1, network_delegate.created_requests());
4108 EXPECT_EQ(0, network_delegate.destroyed_requests());
4109 }
4110 EXPECT_EQ(1, network_delegate.destroyed_requests());
4111}
4112
4113// Tests that the network delegate can asynchronously complete OnAuthRequired
4114// by setting credentials.
4115TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554116 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364117
4118 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304119 BlockingNetworkDelegate network_delegate(
4120 BlockingNetworkDelegate::AUTO_CALLBACK);
4121 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364122 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364123 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4124
[email protected]f3cf9802011-10-28 18:44:584125 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364126 network_delegate.set_auth_credentials(auth_credentials);
4127
[email protected]ef2bf422012-05-11 03:27:094128 TestURLRequestContext context(true);
4129 context.set_network_delegate(&network_delegate);
4130 context.Init();
[email protected]c2911d72011-10-03 22:16:364131
4132 {
tommycli59a63432015-11-06 00:10:554133 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364134 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194135 r->Start();
[email protected]255620da2013-08-19 13:14:294136 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364137
[email protected]f7022f32014-08-21 16:32:194138 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4139 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:364140
[email protected]f7022f32014-08-21 16:32:194141 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364142 EXPECT_FALSE(d.auth_required_called());
4143 EXPECT_EQ(1, network_delegate.created_requests());
4144 EXPECT_EQ(0, network_delegate.destroyed_requests());
4145 }
4146 EXPECT_EQ(1, network_delegate.destroyed_requests());
4147}
4148
4149// Tests that the network delegate can asynchronously complete OnAuthRequired
4150// by cancelling authentication.
4151TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554152 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364153
4154 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304155 BlockingNetworkDelegate network_delegate(
4156 BlockingNetworkDelegate::AUTO_CALLBACK);
4157 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364158 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364159 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4160
[email protected]ef2bf422012-05-11 03:27:094161 TestURLRequestContext context(true);
4162 context.set_network_delegate(&network_delegate);
4163 context.Init();
[email protected]c2911d72011-10-03 22:16:364164
4165 {
tommycli59a63432015-11-06 00:10:554166 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364167 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194168 r->Start();
[email protected]255620da2013-08-19 13:14:294169 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364170
[email protected]f7022f32014-08-21 16:32:194171 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4172 EXPECT_EQ(OK, r->status().error());
4173 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364174 EXPECT_FALSE(d.auth_required_called());
4175 EXPECT_EQ(1, network_delegate.created_requests());
4176 EXPECT_EQ(0, network_delegate.destroyed_requests());
4177 }
4178 EXPECT_EQ(1, network_delegate.destroyed_requests());
4179}
4180
[email protected]9045b8822012-01-13 20:35:354181// Tests that we can handle when a network request was canceled while we were
4182// waiting for the network delegate.
4183// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4184TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554185 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354186
4187 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304188 BlockingNetworkDelegate network_delegate(
4189 BlockingNetworkDelegate::USER_CALLBACK);
4190 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354191
[email protected]ef2bf422012-05-11 03:27:094192 TestURLRequestContext context(true);
4193 context.set_network_delegate(&network_delegate);
4194 context.Init();
[email protected]9045b8822012-01-13 20:35:354195
4196 {
[email protected]f7022f32014-08-21 16:32:194197 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554198 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354199
[email protected]f7022f32014-08-21 16:32:194200 r->Start();
[email protected]255620da2013-08-19 13:14:294201 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304202 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4203 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354204 EXPECT_EQ(0, network_delegate.completed_requests());
4205 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194206 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354207 // Ensure that network delegate is notified.
4208 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194209 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4210 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354211 EXPECT_EQ(1, network_delegate.created_requests());
4212 EXPECT_EQ(0, network_delegate.destroyed_requests());
4213 }
4214 EXPECT_EQ(1, network_delegate.destroyed_requests());
4215}
4216
4217// Tests that we can handle when a network request was canceled while we were
4218// waiting for the network delegate.
4219// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
4220TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554221 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354222
4223 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304224 BlockingNetworkDelegate network_delegate(
4225 BlockingNetworkDelegate::USER_CALLBACK);
4226 network_delegate.set_block_on(
4227 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354228
[email protected]ef2bf422012-05-11 03:27:094229 TestURLRequestContext context(true);
4230 context.set_network_delegate(&network_delegate);
4231 context.Init();
[email protected]9045b8822012-01-13 20:35:354232
4233 {
[email protected]f7022f32014-08-21 16:32:194234 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554235 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354236
[email protected]f7022f32014-08-21 16:32:194237 r->Start();
[email protected]255620da2013-08-19 13:14:294238 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304239 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4240 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354241 EXPECT_EQ(0, network_delegate.completed_requests());
4242 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194243 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354244 // Ensure that network delegate is notified.
4245 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194246 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4247 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354248 EXPECT_EQ(1, network_delegate.created_requests());
4249 EXPECT_EQ(0, network_delegate.destroyed_requests());
4250 }
4251 EXPECT_EQ(1, network_delegate.destroyed_requests());
4252}
4253
4254// Tests that we can handle when a network request was canceled while we were
4255// waiting for the network delegate.
4256// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4257TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554258 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354259
4260 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304261 BlockingNetworkDelegate network_delegate(
4262 BlockingNetworkDelegate::USER_CALLBACK);
4263 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354264
[email protected]ef2bf422012-05-11 03:27:094265 TestURLRequestContext context(true);
4266 context.set_network_delegate(&network_delegate);
4267 context.Init();
[email protected]9045b8822012-01-13 20:35:354268
4269 {
[email protected]f7022f32014-08-21 16:32:194270 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554271 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354272
[email protected]f7022f32014-08-21 16:32:194273 r->Start();
[email protected]255620da2013-08-19 13:14:294274 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304275 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4276 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354277 EXPECT_EQ(0, network_delegate.completed_requests());
4278 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194279 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354280 // Ensure that network delegate is notified.
4281 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194282 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4283 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354284 EXPECT_EQ(1, network_delegate.created_requests());
4285 EXPECT_EQ(0, network_delegate.destroyed_requests());
4286 }
4287 EXPECT_EQ(1, network_delegate.destroyed_requests());
4288}
4289
4290// Tests that we can handle when a network request was canceled while we were
4291// waiting for the network delegate.
4292// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024293TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554294 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354295
4296 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304297 BlockingNetworkDelegate network_delegate(
4298 BlockingNetworkDelegate::USER_CALLBACK);
4299 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354300
[email protected]ef2bf422012-05-11 03:27:094301 TestURLRequestContext context(true);
4302 context.set_network_delegate(&network_delegate);
4303 context.Init();
[email protected]9045b8822012-01-13 20:35:354304
4305 {
[email protected]f7022f32014-08-21 16:32:194306 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554307 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354308
[email protected]f7022f32014-08-21 16:32:194309 r->Start();
[email protected]255620da2013-08-19 13:14:294310 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304311 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4312 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354313 EXPECT_EQ(0, network_delegate.completed_requests());
4314 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194315 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354316 // Ensure that network delegate is notified.
4317 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194318 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4319 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354320 EXPECT_EQ(1, network_delegate.created_requests());
4321 EXPECT_EQ(0, network_delegate.destroyed_requests());
4322 }
4323 EXPECT_EQ(1, network_delegate.destroyed_requests());
4324}
4325
tommycli59a63432015-11-06 00:10:554326namespace {
4327
4328scoped_ptr<test_server::HttpResponse> HandleServerAuthConnect(
4329 const test_server::HttpRequest& request) {
4330 if (request.headers.find("Host") == request.headers.end() ||
4331 request.headers.at("Host") != "www.server-auth.com" ||
4332 request.method != test_server::METHOD_CONNECT) {
4333 return nullptr;
4334 }
4335
4336 scoped_ptr<test_server::BasicHttpResponse> http_response(
4337 new test_server::BasicHttpResponse);
4338 http_response->set_code(HTTP_UNAUTHORIZED);
4339 http_response->AddCustomHeader("WWW-Authenticate",
4340 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:484341 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554342}
4343
4344} // namespace
4345
4346// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114347// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554348// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354349TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554350 http_test_server()->RegisterRequestHandler(
4351 base::Bind(&HandleServerAuthConnect));
4352 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114353
[email protected]ceefd7fd2012-11-29 00:36:244354 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044355 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554356 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504357
[email protected]dc651782009-02-14 01:45:084358 TestDelegate d;
4359 {
[email protected]f7022f32014-08-21 16:32:194360 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364361 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084362
[email protected]f7022f32014-08-21 16:32:194363 r->Start();
4364 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084365
[email protected]255620da2013-08-19 13:14:294366 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084367
[email protected]f7022f32014-08-21 16:32:194368 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:154369 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:194370 EXPECT_TRUE(r->proxy_server().IsEmpty());
4371 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:084372 }
4373}
4374
[email protected]b89290212009-08-14 22:37:354375TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554376 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114377
initial.commit586acc5fe2008-07-26 22:42:524378 TestDelegate d;
4379 {
[email protected]f7022f32014-08-21 16:32:194380 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554381 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524382
[email protected]f7022f32014-08-21 16:32:194383 r->Start();
4384 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524385
[email protected]255620da2013-08-19 13:14:294386 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524387
4388 EXPECT_EQ(1, d.response_started_count());
4389 EXPECT_FALSE(d.received_data_before_response());
4390 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554391 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194392 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554393 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194394 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164395
[email protected]9e743cd2010-03-16 07:03:534396 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524397 }
initial.commit586acc5fe2008-07-26 22:42:524398}
4399
[email protected]263163f2012-06-14 22:40:344400// This test has the server send a large number of cookies to the client.
4401// To ensure that no number of cookies causes a crash, a galloping binary
4402// search is used to estimate that maximum number of cookies that are accepted
4403// by the browser. Beyond the maximum number, the request will fail with
4404// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304405#if defined(OS_WIN)
4406// http://crbug.com/177916
4407#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4408#else
4409#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4410#endif // defined(OS_WIN)
4411TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554412 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344413
4414 int lower_bound = 0;
4415 int upper_bound = 1;
4416
4417 // Double the number of cookies until the response header limits are
4418 // exceeded.
4419 while (DoManyCookiesRequest(upper_bound)) {
4420 lower_bound = upper_bound;
4421 upper_bound *= 2;
4422 ASSERT_LT(upper_bound, 1000000);
4423 }
4424
pkasting6b68a162014-12-01 22:10:294425 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344426 if (tolerance < 2)
4427 tolerance = 2;
4428
4429 // Perform a binary search to find the highest possible number of cookies,
4430 // within the desired tolerance.
4431 while (upper_bound - lower_bound >= tolerance) {
4432 int num_cookies = (lower_bound + upper_bound) / 2;
4433
4434 if (DoManyCookiesRequest(num_cookies))
4435 lower_bound = num_cookies;
4436 else
4437 upper_bound = num_cookies;
4438 }
4439 // Success: the test did not crash.
4440}
4441
[email protected]b89290212009-08-14 22:37:354442TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554443 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114444
initial.commit586acc5fe2008-07-26 22:42:524445 TestDelegate d;
4446 {
[email protected]f7022f32014-08-21 16:32:194447 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554448 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524449
[email protected]f7022f32014-08-21 16:32:194450 r->Start();
4451 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524452
[email protected]255620da2013-08-19 13:14:294453 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524454
4455 EXPECT_EQ(1, d.response_started_count());
4456 EXPECT_FALSE(d.received_data_before_response());
4457 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554458 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194459 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554460 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194461 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524462 }
[email protected]5d7b373e2009-09-02 07:19:034463}
4464
[email protected]79e1fd62013-06-20 06:50:044465TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554466 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044467
4468 TestDelegate d;
4469 {
tommycli59a63432015-11-06 00:10:554470 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:364471 scoped_ptr<URLRequest> r(
4472 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044473
4474 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194475 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044476
[email protected]f7022f32014-08-21 16:32:194477 r->Start();
4478 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044479
[email protected]255620da2013-08-19 13:14:294480 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044481
4482 EXPECT_EQ(1, d.response_started_count());
4483 EXPECT_FALSE(d.received_data_before_response());
4484 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554485 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194486 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554487 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194488 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044489
4490 EXPECT_TRUE(d.have_full_request_headers());
4491 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4492 }
4493}
4494
[email protected]58e32bb2013-01-21 18:23:254495TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554496 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254497
4498 TestDelegate d;
4499 {
[email protected]f7022f32014-08-21 16:32:194500 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554501 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254502
[email protected]f7022f32014-08-21 16:32:194503 r->Start();
4504 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254505
[email protected]255620da2013-08-19 13:14:294506 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254507
4508 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194509 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254510 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4511
4512 EXPECT_EQ(1, d.response_started_count());
4513 EXPECT_FALSE(d.received_data_before_response());
4514 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554515 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194516 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554517 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194518 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254519 }
4520}
4521
tommycli59a63432015-11-06 00:10:554522// TODO(svaldez): Update tests to use EmbeddedTestServer.
4523#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394524TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:554525 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
4526 SpawnedTestServer::kLocalhost,
4527 base::FilePath(kTestFilePath));
4528
4529 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:394530
4531 // Parameter that specifies the Content-Length field in the response:
4532 // C - Compressed length.
4533 // U - Uncompressed length.
4534 // L - Large length (larger than both C & U).
4535 // M - Medium length (between C & U).
4536 // S - Small length (smaller than both C & U).
4537 const char test_parameters[] = "CULMS";
4538 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4539 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444540 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394541 // S has too little data, but we seem to accept it.
4542 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374543 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394544
4545 for (int i = 0; i < num_tests ; i++) {
4546 TestDelegate d;
4547 {
tommycli59a63432015-11-06 00:10:554548 std::string test_file = base::StringPrintf(
4549 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394550
[email protected]ceefd7fd2012-11-29 00:36:244551 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094552 TestURLRequestContext context(true);
4553 context.set_network_delegate(&network_delegate);
4554 context.Init();
[email protected]87a09a92011-07-14 15:50:504555
[email protected]f7022f32014-08-21 16:32:194556 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554557 test_server.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194558 r->Start();
4559 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394560
[email protected]255620da2013-08-19 13:14:294561 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394562
4563 EXPECT_EQ(1, d.response_started_count());
4564 EXPECT_FALSE(d.received_data_before_response());
4565 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194566 << " status = " << r->status().status()
4567 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394568 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194569 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394570 << " Parameter = \"" << test_file << "\"";
4571 } else {
[email protected]f7022f32014-08-21 16:32:194572 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4573 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394574 << " Parameter = \"" << test_file << "\"";
4575 }
4576 }
4577 }
4578}
tommycli59a63432015-11-06 00:10:554579#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394580
tbansala1caf9612015-06-01 20:24:184581TEST_F(URLRequestTestHTTP, NetworkQualityEstimator) {
tommycli59a63432015-11-06 00:10:554582 ASSERT_TRUE(http_test_server()->Start());
tbansalea2fb8c2015-05-22 22:23:004583 // Enable requests to local host to be used for network quality estimation.
tbansalb177b5392015-06-25 11:13:024584 std::map<std::string, std::string> variation_params;
tbansal1c92d5b2015-08-14 20:14:434585 NetworkQualityEstimator estimator(scoped_ptr<net::ExternalEstimateProvider>(),
4586 variation_params, true, true);
tbansalea2fb8c2015-05-22 22:23:004587
4588 TestDelegate d;
4589 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4590 TestURLRequestContext context(true);
4591 context.set_network_quality_estimator(&estimator);
4592 context.set_network_delegate(&network_delegate);
4593 context.Init();
4594
tommycli59a63432015-11-06 00:10:554595 std::string url = "/defaultresponse";
tbansalea2fb8c2015-05-22 22:23:004596
tommycli59a63432015-11-06 00:10:554597 scoped_ptr<URLRequest> r(context.CreateRequest(
4598 http_test_server()->GetURL(url), DEFAULT_PRIORITY, &d));
tbansalea2fb8c2015-05-22 22:23:004599 r->Start();
4600
4601 base::RunLoop().Run();
4602
tbansal9533b6f2015-08-11 22:06:084603 base::TimeDelta rtt;
4604 int32_t kbps;
4605 EXPECT_TRUE(estimator.GetRTTEstimate(&rtt));
4606 EXPECT_TRUE(estimator.GetDownlinkThroughputKbpsEstimate(&kbps));
4607 EXPECT_GE(rtt, base::TimeDelta());
4608 EXPECT_LT(rtt, base::TimeDelta::Max());
4609 EXPECT_GT(kbps, 0);
tbansalea2fb8c2015-05-22 22:23:004610
4611 // Verify that histograms are not populated. They should populate only when
4612 // there is a change in ConnectionType.
4613 base::HistogramTester histogram_tester;
4614 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 0);
4615 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 0);
4616
4617 NetworkChangeNotifier::NotifyObserversOfConnectionTypeChangeForTests(
4618 NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI);
4619 base::MessageLoop::current()->RunUntilIdle();
4620 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 1);
4621 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 1);
4622}
4623
[email protected]58e32bb2013-01-21 18:23:254624TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:554625 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254626
tommycli59a63432015-11-06 00:10:554627 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454628 GURL original_url =
tommycli59a63432015-11-06 00:10:554629 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254630 TestDelegate d;
davidben151423e2015-03-23 18:48:364631 scoped_ptr<URLRequest> req(
4632 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194633 req->Start();
[email protected]255620da2013-08-19 13:14:294634 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254635
4636 EXPECT_EQ(1, d.response_started_count());
4637 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194638 EXPECT_EQ(destination_url, req->url());
4639 EXPECT_EQ(original_url, req->original_url());
4640 ASSERT_EQ(2U, req->url_chain().size());
4641 EXPECT_EQ(original_url, req->url_chain()[0]);
4642 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254643
4644 LoadTimingInfo load_timing_info_before_redirect;
4645 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4646 &load_timing_info_before_redirect));
4647 TestLoadTimingNotReused(load_timing_info_before_redirect,
4648 CONNECT_TIMING_HAS_DNS_TIMES);
4649
4650 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194651 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254652 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4653
4654 // Check that a new socket was used on redirect, since the server does not
4655 // supposed keep-alive sockets, and that the times before the redirect are
4656 // before the ones recorded for the second request.
4657 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4658 load_timing_info.socket_log_id);
4659 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4660 load_timing_info.connect_timing.connect_start);
4661}
4662
[email protected]8f1ac082011-04-19 21:14:134663TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:554664 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:134665
tommycli59a63432015-11-06 00:10:554666 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454667 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:554668 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
4669 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
4670 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:134671 TestDelegate d;
davidben151423e2015-03-23 18:48:364672 scoped_ptr<URLRequest> req(
4673 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194674 req->Start();
[email protected]255620da2013-08-19 13:14:294675 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134676
4677 EXPECT_EQ(1, d.response_started_count());
4678 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194679 EXPECT_EQ(destination_url, req->url());
4680 EXPECT_EQ(original_url, req->original_url());
4681 ASSERT_EQ(3U, req->url_chain().size());
4682 EXPECT_EQ(original_url, req->url_chain()[0]);
4683 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4684 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134685}
4686
[email protected]abe1c4a2013-10-25 19:28:514687// First and second pieces of information logged by delegates to URLRequests.
4688const char kFirstDelegateInfo[] = "Wonderful delegate";
4689const char kSecondDelegateInfo[] = "Exciting delegate";
4690
4691// Logs delegate information to a URLRequest. The first string is logged
4692// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4693// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4694// another asynchronous call is used to clear the delegate information
4695// before calling a callback. The object then deletes itself.
4696class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4697 public:
4698 typedef base::Callback<void()> Callback;
4699
4700 // Each time delegate information is added to the URLRequest, the resulting
4701 // load state is checked. The expected load state after each request is
4702 // passed in as an argument.
4703 static void Run(URLRequest* url_request,
4704 LoadState expected_first_load_state,
4705 LoadState expected_second_load_state,
4706 LoadState expected_third_load_state,
4707 const Callback& callback) {
4708 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4709 url_request,
4710 expected_first_load_state,
4711 expected_second_load_state,
4712 expected_third_load_state,
4713 callback);
4714 logger->Start();
4715 }
4716
4717 // Checks that the log entries, starting with log_position, contain the
4718 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4719 // recorded. Returns the index of entry after the expected number of
4720 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464721 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514722 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514723 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4724 if (log_position + 3 >= entries.size()) {
4725 ADD_FAILURE() << "Not enough log entries";
4726 return entries.size();
4727 }
4728 std::string delegate_info;
4729 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4730 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4731 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4732 &delegate_info));
4733 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4734
4735 ++log_position;
4736 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4737 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4738
4739 ++log_position;
4740 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4741 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4742 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4743 &delegate_info));
4744 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4745
4746 ++log_position;
4747 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4748 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4749
4750 return log_position + 1;
4751 }
4752
[email protected]1826a402014-01-08 15:40:484753 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4754 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464755 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4756 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484757 log_position =
4758 ExpectLogContainsSomewhereAfter(entries,
4759 log_position,
4760 NetLog::TYPE_URL_REQUEST_DELEGATE,
4761 NetLog::PHASE_BEGIN);
4762 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4763 entries[log_position + 1].type);
4764 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4765 return log_position + 1;
4766 }
4767
[email protected]abe1c4a2013-10-25 19:28:514768 private:
4769 friend class base::RefCounted<AsyncDelegateLogger>;
4770
4771 AsyncDelegateLogger(URLRequest* url_request,
4772 LoadState expected_first_load_state,
4773 LoadState expected_second_load_state,
4774 LoadState expected_third_load_state,
4775 const Callback& callback)
4776 : url_request_(url_request),
4777 expected_first_load_state_(expected_first_load_state),
4778 expected_second_load_state_(expected_second_load_state),
4779 expected_third_load_state_(expected_third_load_state),
4780 callback_(callback) {
4781 }
4782
4783 ~AsyncDelegateLogger() {}
4784
4785 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534786 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514787 LoadStateWithParam load_state = url_request_->GetLoadState();
4788 EXPECT_EQ(expected_first_load_state_, load_state.state);
4789 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454790 base::ThreadTaskRunnerHandle::Get()->PostTask(
4791 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514792 }
4793
4794 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534795 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514796 LoadStateWithParam load_state = url_request_->GetLoadState();
4797 EXPECT_EQ(expected_second_load_state_, load_state.state);
4798 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4799 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4800 } else {
4801 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4802 }
skyostil4891b25b2015-06-11 11:43:454803 base::ThreadTaskRunnerHandle::Get()->PostTask(
4804 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514805 }
4806
4807 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534808 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514809 LoadStateWithParam load_state = url_request_->GetLoadState();
4810 EXPECT_EQ(expected_third_load_state_, load_state.state);
4811 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084812 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514813 callback_.Run();
4814 }
4815
4816 URLRequest* url_request_;
4817 const int expected_first_load_state_;
4818 const int expected_second_load_state_;
4819 const int expected_third_load_state_;
4820 const Callback callback_;
4821
4822 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4823};
4824
4825// NetworkDelegate that logs delegate information before a request is started,
4826// before headers are sent, when headers are read, and when auth information
4827// is requested. Uses AsyncDelegateLogger.
4828class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4829 public:
4830 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204831 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514832
4833 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204834 int OnBeforeURLRequest(URLRequest* request,
4835 const CompletionCallback& callback,
4836 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514837 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4838 return RunCallbackAsynchronously(request, callback);
4839 }
4840
dchengb03027d2014-10-21 12:00:204841 int OnBeforeSendHeaders(URLRequest* request,
4842 const CompletionCallback& callback,
4843 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514844 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4845 return RunCallbackAsynchronously(request, callback);
4846 }
4847
dchengb03027d2014-10-21 12:00:204848 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514849 URLRequest* request,
4850 const CompletionCallback& callback,
4851 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164852 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134853 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164854 TestNetworkDelegate::OnHeadersReceived(request,
4855 callback,
[email protected]abe1c4a2013-10-25 19:28:514856 original_response_headers,
[email protected]5f714132014-03-26 10:41:164857 override_response_headers,
4858 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514859 return RunCallbackAsynchronously(request, callback);
4860 }
4861
dchengb03027d2014-10-21 12:00:204862 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514863 URLRequest* request,
4864 const AuthChallengeInfo& auth_info,
4865 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134866 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514867 AsyncDelegateLogger::Run(
4868 request,
4869 LOAD_STATE_WAITING_FOR_DELEGATE,
4870 LOAD_STATE_WAITING_FOR_DELEGATE,
4871 LOAD_STATE_WAITING_FOR_DELEGATE,
4872 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4873 callback, credentials));
4874 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4875 }
4876
4877 private:
4878 static int RunCallbackAsynchronously(
4879 URLRequest* request,
4880 const CompletionCallback& callback) {
4881 AsyncDelegateLogger::Run(
4882 request,
4883 LOAD_STATE_WAITING_FOR_DELEGATE,
4884 LOAD_STATE_WAITING_FOR_DELEGATE,
4885 LOAD_STATE_WAITING_FOR_DELEGATE,
4886 base::Bind(callback, OK));
4887 return ERR_IO_PENDING;
4888 }
4889
4890 static void SetAuthAndResume(const AuthCallback& callback,
4891 AuthCredentials* credentials) {
4892 *credentials = AuthCredentials(kUser, kSecret);
4893 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4894 }
4895
4896 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4897};
4898
4899// URLRequest::Delegate that logs delegate information when the headers
4900// are received, when each read completes, and during redirects. Uses
4901// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4902//
4903// Inherits from TestDelegate to reuse the TestDelegate code to handle
4904// advancing to the next step in most cases, as well as cancellation.
4905class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4906 public:
4907 enum CancelStage {
4908 NO_CANCEL = 0,
4909 CANCEL_ON_RECEIVED_REDIRECT,
4910 CANCEL_ON_RESPONSE_STARTED,
4911 CANCEL_ON_READ_COMPLETED
4912 };
4913
4914 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4915 : cancel_stage_(cancel_stage) {
4916 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4917 set_cancel_in_received_redirect(true);
4918 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4919 set_cancel_in_response_started(true);
4920 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4921 set_cancel_in_received_data(true);
4922 }
dchengb03027d2014-10-21 12:00:204923 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514924
4925 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204926 void OnReceivedRedirect(URLRequest* request,
4927 const RedirectInfo& redirect_info,
4928 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514929 *defer_redirect = true;
4930 AsyncDelegateLogger::Run(
4931 request,
4932 LOAD_STATE_WAITING_FOR_DELEGATE,
4933 LOAD_STATE_WAITING_FOR_DELEGATE,
4934 LOAD_STATE_WAITING_FOR_DELEGATE,
4935 base::Bind(
4936 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594937 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514938 }
4939
dchengb03027d2014-10-21 12:00:204940 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514941 AsyncDelegateLogger::Run(
4942 request,
4943 LOAD_STATE_WAITING_FOR_DELEGATE,
4944 LOAD_STATE_WAITING_FOR_DELEGATE,
4945 LOAD_STATE_WAITING_FOR_DELEGATE,
4946 base::Bind(
4947 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4948 base::Unretained(this), request));
4949 }
4950
dchengb03027d2014-10-21 12:00:204951 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514952 AsyncDelegateLogger::Run(
4953 request,
4954 LOAD_STATE_IDLE,
4955 LOAD_STATE_IDLE,
4956 LOAD_STATE_IDLE,
4957 base::Bind(
4958 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4959 base::Unretained(this), request, bytes_read));
4960 }
4961
4962 private:
4963 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594964 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514965 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594966 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514967 // FollowDeferredRedirect should not be called after cancellation.
4968 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4969 return;
4970 if (!defer_redirect)
4971 request->FollowDeferredRedirect();
4972 }
4973
4974 void OnResponseStartedLoggingComplete(URLRequest* request) {
4975 // The parent class continues the request.
4976 TestDelegate::OnResponseStarted(request);
4977 }
4978
4979 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4980 // The parent class continues the request.
4981 TestDelegate::OnReadCompleted(request, bytes_read);
4982 }
4983
4984 const CancelStage cancel_stage_;
4985
4986 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4987};
4988
4989// Tests handling of delegate info before a request starts.
4990TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:554991 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:514992
4993 TestDelegate request_delegate;
4994 TestURLRequestContext context(true);
4995 context.set_network_delegate(NULL);
4996 context.set_net_log(&net_log_);
4997 context.Init();
4998
4999 {
davidben151423e2015-03-23 18:48:365000 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555001 context.CreateRequest(http_test_server()->GetURL("/defaultresponse"),
davidben151423e2015-03-23 18:48:365002 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195003 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515004 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085005 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515006
5007 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195008 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515009 LOAD_STATE_WAITING_FOR_DELEGATE,
5010 LOAD_STATE_WAITING_FOR_DELEGATE,
5011 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195012 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515013
5014 base::RunLoop().Run();
5015
[email protected]f7022f32014-08-21 16:32:195016 EXPECT_EQ(200, r->GetResponseCode());
5017 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515018 }
5019
mmenke43758e62015-05-04 21:09:465020 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515021 net_log_.GetEntries(&entries);
5022 size_t log_position = ExpectLogContainsSomewhereAfter(
5023 entries,
5024 0,
5025 NetLog::TYPE_DELEGATE_INFO,
5026 NetLog::PHASE_BEGIN);
5027
5028 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5029
5030 // Nothing else should add any delegate info to the request.
5031 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5032 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5033}
5034
5035// Tests handling of delegate info from a network delegate.
5036TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555037 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515038
5039 TestDelegate request_delegate;
5040 AsyncLoggingNetworkDelegate network_delegate;
5041 TestURLRequestContext context(true);
5042 context.set_network_delegate(&network_delegate);
5043 context.set_net_log(&net_log_);
5044 context.Init();
5045
5046 {
davidben151423e2015-03-23 18:48:365047 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555048 context.CreateRequest(http_test_server()->GetURL("/simple.html"),
davidben151423e2015-03-23 18:48:365049 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195050 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515051 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085052 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515053
[email protected]f7022f32014-08-21 16:32:195054 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515055 base::RunLoop().Run();
5056
[email protected]f7022f32014-08-21 16:32:195057 EXPECT_EQ(200, r->GetResponseCode());
5058 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515059 EXPECT_EQ(1, network_delegate.created_requests());
5060 EXPECT_EQ(0, network_delegate.destroyed_requests());
5061 }
5062 EXPECT_EQ(1, network_delegate.destroyed_requests());
5063
5064 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465065 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515066 net_log_.GetEntries(&entries);
5067 for (size_t i = 0; i < 3; ++i) {
5068 log_position = ExpectLogContainsSomewhereAfter(
5069 entries,
5070 log_position + 1,
5071 NetLog::TYPE_URL_REQUEST_DELEGATE,
5072 NetLog::PHASE_BEGIN);
5073
5074 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5075 log_position + 1);
5076
5077 ASSERT_LT(log_position, entries.size());
5078 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5079 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485080
5081 if (i == 1) {
5082 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5083 entries, log_position + 1);
5084 }
[email protected]abe1c4a2013-10-25 19:28:515085 }
5086
5087 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5088 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5089}
5090
5091// Tests handling of delegate info from a network delegate in the case of an
5092// HTTP redirect.
5093TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555094 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515095
5096 TestDelegate request_delegate;
5097 AsyncLoggingNetworkDelegate network_delegate;
5098 TestURLRequestContext context(true);
5099 context.set_network_delegate(&network_delegate);
5100 context.set_net_log(&net_log_);
5101 context.Init();
5102
5103 {
[email protected]f7022f32014-08-21 16:32:195104 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555105 http_test_server()->GetURL("/server-redirect?simple.html"),
5106 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195107 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515108 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085109 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515110
[email protected]f7022f32014-08-21 16:32:195111 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515112 base::RunLoop().Run();
5113
[email protected]f7022f32014-08-21 16:32:195114 EXPECT_EQ(200, r->GetResponseCode());
5115 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515116 EXPECT_EQ(2, network_delegate.created_requests());
5117 EXPECT_EQ(0, network_delegate.destroyed_requests());
5118 }
5119 EXPECT_EQ(1, network_delegate.destroyed_requests());
5120
5121 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465122 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515123 net_log_.GetEntries(&entries);
5124 // The NetworkDelegate logged information in OnBeforeURLRequest,
5125 // OnBeforeSendHeaders, and OnHeadersReceived.
5126 for (size_t i = 0; i < 3; ++i) {
5127 log_position = ExpectLogContainsSomewhereAfter(
5128 entries,
5129 log_position + 1,
5130 NetLog::TYPE_URL_REQUEST_DELEGATE,
5131 NetLog::PHASE_BEGIN);
5132
5133 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5134 log_position + 1);
5135
5136 ASSERT_LT(log_position, entries.size());
5137 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5138 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485139
5140 if (i == 1) {
5141 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5142 entries, log_position + 1);
5143 }
[email protected]abe1c4a2013-10-25 19:28:515144 }
5145
5146 // The URLRequest::Delegate then gets informed about the redirect.
5147 log_position = ExpectLogContainsSomewhereAfter(
5148 entries,
5149 log_position + 1,
5150 NetLog::TYPE_URL_REQUEST_DELEGATE,
5151 NetLog::PHASE_BEGIN);
5152
5153 // The NetworkDelegate logged information in the same three events as before.
5154 for (size_t i = 0; i < 3; ++i) {
5155 log_position = ExpectLogContainsSomewhereAfter(
5156 entries,
5157 log_position + 1,
5158 NetLog::TYPE_URL_REQUEST_DELEGATE,
5159 NetLog::PHASE_BEGIN);
5160
5161 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5162 log_position + 1);
5163
5164 ASSERT_LT(log_position, entries.size());
5165 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5166 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5167 }
5168
5169 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5170 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5171}
5172
5173// Tests handling of delegate info from a network delegate in the case of HTTP
5174// AUTH.
5175TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555176 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515177
5178 TestDelegate request_delegate;
5179 AsyncLoggingNetworkDelegate network_delegate;
5180 TestURLRequestContext context(true);
5181 context.set_network_delegate(&network_delegate);
5182 context.set_net_log(&net_log_);
5183 context.Init();
5184
5185 {
davidben151423e2015-03-23 18:48:365186 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555187 context.CreateRequest(http_test_server()->GetURL("/auth-basic"),
davidben151423e2015-03-23 18:48:365188 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195189 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515190 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085191 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515192
[email protected]f7022f32014-08-21 16:32:195193 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515194 base::RunLoop().Run();
5195
[email protected]f7022f32014-08-21 16:32:195196 EXPECT_EQ(200, r->GetResponseCode());
5197 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515198 EXPECT_EQ(1, network_delegate.created_requests());
5199 EXPECT_EQ(0, network_delegate.destroyed_requests());
5200 }
5201 EXPECT_EQ(1, network_delegate.destroyed_requests());
5202
5203 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465204 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515205 net_log_.GetEntries(&entries);
5206 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
5207 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
5208 // OnBeforeURLRequest and OnBeforeSendHeaders.
5209 for (size_t i = 0; i < 6; ++i) {
5210 log_position = ExpectLogContainsSomewhereAfter(
5211 entries,
5212 log_position + 1,
5213 NetLog::TYPE_URL_REQUEST_DELEGATE,
5214 NetLog::PHASE_BEGIN);
5215
5216 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5217 log_position + 1);
5218
5219 ASSERT_LT(log_position, entries.size());
5220 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5221 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485222
5223 if (i == 1) {
5224 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5225 entries, log_position + 1);
5226 }
[email protected]abe1c4a2013-10-25 19:28:515227 }
5228
5229 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5230 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5231}
5232
tommycli59a63432015-11-06 00:10:555233// TODO(svaldez): Update tests to use EmbeddedTestServer.
5234#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515235// Tests handling of delegate info from a URLRequest::Delegate.
5236TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555237 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
5238 SpawnedTestServer::kLocalhost,
5239 base::FilePath(kTestFilePath));
5240
5241 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515242
5243 AsyncLoggingUrlRequestDelegate request_delegate(
5244 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5245 TestURLRequestContext context(true);
5246 context.set_network_delegate(NULL);
5247 context.set_net_log(&net_log_);
5248 context.Init();
5249
5250 {
5251 // A chunked response with delays between chunks is used to make sure that
5252 // attempts by the URLRequest delegate to log information while reading the
5253 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485254 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515255 // that it occurs.
[email protected]f7022f32014-08-21 16:32:195256 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555257 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365258 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195259 LoadStateWithParam load_state = r->GetLoadState();
5260 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515261 base::RunLoop().Run();
5262
[email protected]f7022f32014-08-21 16:32:195263 EXPECT_EQ(200, r->GetResponseCode());
5264 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515265 }
5266
mmenke43758e62015-05-04 21:09:465267 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515268 net_log_.GetEntries(&entries);
5269
[email protected]1826a402014-01-08 15:40:485270 size_t log_position = 0;
5271
5272 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5273 entries, log_position);
5274
[email protected]abe1c4a2013-10-25 19:28:515275 // The delegate info should only have been logged on header complete. Other
5276 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:485277 log_position =
5278 ExpectLogContainsSomewhereAfter(entries,
5279 log_position + 1,
5280 NetLog::TYPE_URL_REQUEST_DELEGATE,
5281 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515282
5283 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5284 log_position + 1);
5285
5286 ASSERT_LT(log_position, entries.size());
5287 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5288 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5289
5290 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5291 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5292 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5293 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5294}
tommycli59a63432015-11-06 00:10:555295#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515296
5297// Tests handling of delegate info from a URLRequest::Delegate in the case of
5298// an HTTP redirect.
5299TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555300 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515301
5302 AsyncLoggingUrlRequestDelegate request_delegate(
5303 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5304 TestURLRequestContext context(true);
5305 context.set_network_delegate(NULL);
5306 context.set_net_log(&net_log_);
5307 context.Init();
5308
5309 {
[email protected]f7022f32014-08-21 16:32:195310 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555311 http_test_server()->GetURL("/server-redirect?simple.html"),
5312 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195313 LoadStateWithParam load_state = r->GetLoadState();
5314 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515315 base::RunLoop().Run();
5316
[email protected]f7022f32014-08-21 16:32:195317 EXPECT_EQ(200, r->GetResponseCode());
5318 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515319 }
5320
mmenke43758e62015-05-04 21:09:465321 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515322 net_log_.GetEntries(&entries);
5323
5324 // Delegate info should only have been logged in OnReceivedRedirect and
5325 // OnResponseStarted.
5326 size_t log_position = 0;
5327 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485328 if (i == 0) {
5329 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5330 entries, log_position) + 1;
5331 }
5332
[email protected]abe1c4a2013-10-25 19:28:515333 log_position = ExpectLogContainsSomewhereAfter(
5334 entries,
5335 log_position,
5336 NetLog::TYPE_URL_REQUEST_DELEGATE,
5337 NetLog::PHASE_BEGIN);
5338
5339 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5340 log_position + 1);
5341
5342 ASSERT_LT(log_position, entries.size());
5343 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5344 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5345 }
5346
5347 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5348 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5349 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5350 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5351}
5352
5353// Tests handling of delegate info from a URLRequest::Delegate in the case of
5354// an HTTP redirect, with cancellation at various points.
5355TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555356 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515357
5358 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5359 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5360 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5361 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5362 };
5363
5364 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5365 ++test_case) {
5366 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5367 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:515368 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:515369 context.set_network_delegate(NULL);
5370 context.set_net_log(&net_log);
5371 context.Init();
5372
5373 {
[email protected]f7022f32014-08-21 16:32:195374 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555375 http_test_server()->GetURL("/server-redirect?simple.html"),
5376 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195377 LoadStateWithParam load_state = r->GetLoadState();
5378 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515379 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195380 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515381 }
5382
mmenke43758e62015-05-04 21:09:465383 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515384 net_log.GetEntries(&entries);
5385
5386 // Delegate info is always logged in both OnReceivedRedirect and
5387 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5388 // OnResponseStarted delegate call is after cancellation, but logging is
5389 // still currently supported in that call.
5390 size_t log_position = 0;
5391 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485392 if (i == 0) {
5393 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5394 entries, log_position) + 1;
5395 }
5396
[email protected]abe1c4a2013-10-25 19:28:515397 log_position = ExpectLogContainsSomewhereAfter(
5398 entries,
5399 log_position,
5400 NetLog::TYPE_URL_REQUEST_DELEGATE,
5401 NetLog::PHASE_BEGIN);
5402
5403 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5404 log_position + 1);
5405
5406 ASSERT_LT(log_position, entries.size());
5407 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5408 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5409 }
5410
5411 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5412 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5413 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5414 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5415 }
5416}
5417
[email protected]847c0fa92012-11-06 16:37:425418namespace {
5419
5420const char kExtraHeader[] = "Allow-Snafu";
5421const char kExtraValue[] = "fubar";
5422
5423class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205424 void OnReceivedRedirect(URLRequest* request,
5425 const RedirectInfo& redirect_info,
5426 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595427 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425428 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5429 }
5430};
5431
5432} // namespace
5433
5434TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555435 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425436
tommycli59a63432015-11-06 00:10:555437 GURL destination_url =
5438 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5439 GURL original_url =
5440 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425441 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:365442 scoped_ptr<URLRequest> req(
5443 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195444 req->Start();
[email protected]255620da2013-08-19 13:14:295445 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425446
5447 std::string value;
[email protected]f7022f32014-08-21 16:32:195448 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425449 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5450 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195451 EXPECT_FALSE(req->is_pending());
5452 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425453 EXPECT_EQ(kExtraValue, d.data_received());
5454}
5455
[email protected]251a1b92012-11-13 11:01:095456namespace {
5457
5458const char kExtraHeaderToRemove[] = "To-Be-Removed";
5459
5460class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205461 void OnReceivedRedirect(URLRequest* request,
5462 const RedirectInfo& redirect_info,
5463 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595464 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095465 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5466 }
5467};
5468
5469} // namespace
5470
5471TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555472 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095473
tommycli59a63432015-11-06 00:10:555474 GURL destination_url = http_test_server()->GetURL(
5475 "/echoheader?" + std::string(kExtraHeaderToRemove));
5476 GURL original_url =
5477 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095478 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:365479 scoped_ptr<URLRequest> req(
5480 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195481 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5482 req->Start();
[email protected]255620da2013-08-19 13:14:295483 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095484
5485 std::string value;
[email protected]f7022f32014-08-21 16:32:195486 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095487 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195488 EXPECT_FALSE(req->is_pending());
5489 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095490 EXPECT_EQ("None", d.data_received());
5491}
5492
[email protected]316c1e5e2012-09-12 15:17:445493TEST_F(URLRequestTestHTTP, CancelTest) {
5494 TestDelegate d;
5495 {
[email protected]f7022f32014-08-21 16:32:195496 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365497 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445498
[email protected]f7022f32014-08-21 16:32:195499 r->Start();
5500 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445501
[email protected]f7022f32014-08-21 16:32:195502 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445503
[email protected]255620da2013-08-19 13:14:295504 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445505
5506 // We expect to receive OnResponseStarted even though the request has been
5507 // cancelled.
5508 EXPECT_EQ(1, d.response_started_count());
5509 EXPECT_EQ(0, d.bytes_received());
5510 EXPECT_FALSE(d.received_data_before_response());
5511 }
5512}
5513
5514TEST_F(URLRequestTestHTTP, CancelTest2) {
tommycli59a63432015-11-06 00:10:555515 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445516
5517 TestDelegate d;
5518 {
[email protected]f7022f32014-08-21 16:32:195519 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555520 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445521
5522 d.set_cancel_in_response_started(true);
5523
[email protected]f7022f32014-08-21 16:32:195524 r->Start();
5525 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445526
[email protected]255620da2013-08-19 13:14:295527 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445528
5529 EXPECT_EQ(1, d.response_started_count());
5530 EXPECT_EQ(0, d.bytes_received());
5531 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195532 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445533 }
5534}
5535
5536TEST_F(URLRequestTestHTTP, CancelTest3) {
tommycli59a63432015-11-06 00:10:555537 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445538
5539 TestDelegate d;
5540 {
[email protected]f7022f32014-08-21 16:32:195541 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555542 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445543
5544 d.set_cancel_in_received_data(true);
5545
[email protected]f7022f32014-08-21 16:32:195546 r->Start();
5547 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445548
[email protected]255620da2013-08-19 13:14:295549 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445550
5551 EXPECT_EQ(1, d.response_started_count());
5552 // There is no guarantee about how much data was received
5553 // before the cancel was issued. It could have been 0 bytes,
5554 // or it could have been all the bytes.
5555 // EXPECT_EQ(0, d.bytes_received());
5556 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195557 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445558 }
5559}
5560
5561TEST_F(URLRequestTestHTTP, CancelTest4) {
tommycli59a63432015-11-06 00:10:555562 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445563
5564 TestDelegate d;
5565 {
[email protected]f7022f32014-08-21 16:32:195566 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555567 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445568
[email protected]f7022f32014-08-21 16:32:195569 r->Start();
5570 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445571
5572 // The request will be implicitly canceled when it is destroyed. The
5573 // test delegate must not post a quit message when this happens because
5574 // this test doesn't actually have a message loop. The quit message would
5575 // get put on this thread's message queue and the next test would exit
5576 // early, causing problems.
5577 d.set_quit_on_complete(false);
5578 }
5579 // expect things to just cleanup properly.
5580
kimwjdalsl2bb4ff02015-12-16 22:06:025581 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:445582 // message loop
5583 EXPECT_FALSE(d.received_data_before_response());
5584 EXPECT_EQ(0, d.bytes_received());
5585}
5586
5587TEST_F(URLRequestTestHTTP, CancelTest5) {
tommycli59a63432015-11-06 00:10:555588 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445589
5590 // populate cache
5591 {
5592 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195593 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555594 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195595 r->Start();
[email protected]255620da2013-08-19 13:14:295596 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195597 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445598 }
5599
5600 // cancel read from cache (see bug 990242)
5601 {
5602 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195603 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555604 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195605 r->Start();
5606 r->Cancel();
[email protected]255620da2013-08-19 13:14:295607 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445608
[email protected]f7022f32014-08-21 16:32:195609 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445610 EXPECT_EQ(1, d.response_started_count());
5611 EXPECT_EQ(0, d.bytes_received());
5612 EXPECT_FALSE(d.received_data_before_response());
5613 }
5614}
5615
5616TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:555617 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445618 HTTPUploadDataOperationTest("POST");
5619}
5620
5621TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:555622 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445623 HTTPUploadDataOperationTest("PUT");
5624}
5625
5626TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:555627 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445628
5629 TestDelegate d;
5630 {
[email protected]f7022f32014-08-21 16:32:195631 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555632 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195633 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445634
[email protected]f7022f32014-08-21 16:32:195635 r->Start();
5636 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445637
[email protected]255620da2013-08-19 13:14:295638 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445639
[email protected]329b68b2012-11-14 17:54:275640 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195641 << "request failed: " << r->status().status()
5642 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445643
5644 EXPECT_FALSE(d.received_data_before_response());
5645 EXPECT_TRUE(d.data_received().empty());
5646 }
5647}
5648
5649TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:555650 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445651
5652 TestDelegate d;
5653 {
[email protected]f7022f32014-08-21 16:32:195654 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555655 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195656 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445657
[email protected]6cdfd7f2013-02-08 20:40:155658 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445659 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025660 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445661
olli.raula6df48b2a2015-11-26 07:40:225662 std::vector<scoped_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445663
[email protected]6cdfd7f2013-02-08 20:40:155664 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445665 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475666 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445667 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
avibf0746c2015-12-09 19:53:145668 element_readers.push_back(make_scoped_ptr(new UploadFileElementReader(
5669 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
5670 std::numeric_limits<uint64_t>::max(), base::Time())));
mmenkecbc2b712014-10-09 20:29:075671 r->set_upload(make_scoped_ptr<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225672 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:445673
[email protected]f7022f32014-08-21 16:32:195674 r->Start();
5675 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445676
[email protected]255620da2013-08-19 13:14:295677 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445678
avibf0746c2015-12-09 19:53:145679 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:295680 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5681 ASSERT_LE(size64, std::numeric_limits<int>::max());
5682 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175683 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445684
[email protected]7600d0b2013-12-08 21:43:305685 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445686
[email protected]329b68b2012-11-14 17:54:275687 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195688 << "request failed: " << r->status().status()
5689 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445690
5691 EXPECT_FALSE(d.received_data_before_response());
5692
[email protected]329b68b2012-11-14 17:54:275693 EXPECT_EQ(size, d.bytes_received());
5694 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445695 }
5696}
5697
[email protected]999dd8c2013-11-12 06:45:545698TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:555699 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:545700
5701 TestDelegate d;
5702 {
[email protected]f7022f32014-08-21 16:32:195703 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555704 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195705 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545706
olli.raula6df48b2a2015-11-26 07:40:225707 std::vector<scoped_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:545708
olli.raula6df48b2a2015-11-26 07:40:225709 element_readers.push_back(make_scoped_ptr(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455710 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545711 base::FilePath(FILE_PATH_LITERAL(
5712 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
avibf0746c2015-12-09 19:53:145713 0, std::numeric_limits<uint64_t>::max(), base::Time())));
mmenkecbc2b712014-10-09 20:29:075714 r->set_upload(make_scoped_ptr<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225715 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:545716
[email protected]f7022f32014-08-21 16:32:195717 r->Start();
5718 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545719
5720 base::RunLoop().Run();
5721
[email protected]999dd8c2013-11-12 06:45:545722 EXPECT_TRUE(d.request_failed());
5723 EXPECT_FALSE(d.received_data_before_response());
5724 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195725 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5726 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545727 }
5728}
5729
[email protected]316c1e5e2012-09-12 15:17:445730TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:555731 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445732
5733 TestDelegate d;
5734 {
[email protected]f7022f32014-08-21 16:32:195735 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555736 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195737 r->EnableChunkedUpload();
5738 r->set_method("POST");
5739 AddChunksToUpload(r.get());
5740 r->Start();
5741 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445742
[email protected]255620da2013-08-19 13:14:295743 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445744
[email protected]f7022f32014-08-21 16:32:195745 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445746 }
5747}
5748
[email protected]329b68b2012-11-14 17:54:275749TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:555750 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:275751
5752 TestDelegate d;
5753 {
[email protected]f7022f32014-08-21 16:32:195754 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555755 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195756 r->EnableChunkedUpload();
5757 r->set_method("POST");
5758 r->Start();
5759 EXPECT_TRUE(r->is_pending());
5760 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295761 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275762
[email protected]f7022f32014-08-21 16:32:195763 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275764 }
5765}
5766
[email protected]316c1e5e2012-09-12 15:17:445767TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:555768 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445769
5770 TestDelegate d;
5771 {
[email protected]f7022f32014-08-21 16:32:195772 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555773 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195774 r->EnableChunkedUpload();
5775 r->set_method("POST");
5776 r->Start();
5777 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445778
[email protected]255620da2013-08-19 13:14:295779 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195780 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295781 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445782
[email protected]f7022f32014-08-21 16:32:195783 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445784 }
5785}
5786
5787TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:555788 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445789
5790 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195791 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555792 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195793 req->Start();
[email protected]255620da2013-08-19 13:14:295794 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445795
[email protected]f7022f32014-08-21 16:32:195796 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445797
5798 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195799 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445800
5801 std::string header;
5802 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5803 EXPECT_EQ("private", header);
5804
5805 header.clear();
5806 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5807 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5808
5809 // The response has two "X-Multiple-Entries" headers.
5810 // This verfies our output has them concatenated together.
5811 header.clear();
5812 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5813 EXPECT_EQ("a, b", header);
5814}
5815
tommycli59a63432015-11-06 00:10:555816// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
5817// security state. (see http://crbug.com/550977).
5818#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:465819TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:555820 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5821 https_test_server.SetSSLConfig(
5822 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5823 https_test_server.ServeFilesFromSourceDirectory(
5824 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465825 ASSERT_TRUE(https_test_server.Start());
5826
tommycli59a63432015-11-06 00:10:555827 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:465828 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195829 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555830 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195831 request->Start();
[email protected]255620da2013-08-19 13:14:295832 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465833
5834 TransportSecurityState* security_state =
5835 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405836 TransportSecurityState::STSState sts_state;
5837 TransportSecurityState::PKPState pkp_state;
5838 EXPECT_TRUE(
5839 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5840 EXPECT_FALSE(
5841 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5842 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5843 sts_state.upgrade_mode);
5844 EXPECT_TRUE(sts_state.include_subdomains);
5845 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:035846#if defined(OS_ANDROID)
5847 // Android's CertVerifyProc does not (yet) handle pins.
5848#else
martijnc0d6b622015-06-30 19:14:405849 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035850#endif
[email protected]37fd55fb2013-06-29 13:13:275851}
5852
estarka5da76702015-04-09 04:00:165853TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555854 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5855 https_test_server.ServeFilesFromSourceDirectory(
5856 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165857 ASSERT_TRUE(https_test_server.Start());
5858 // Make sure this test fails if the test server is changed to not
5859 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555860 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5861 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165862
5863 TestDelegate d;
5864 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555865 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:165866 request->Start();
5867 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:165868 TransportSecurityState* security_state =
5869 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405870 TransportSecurityState::STSState sts_state;
5871 EXPECT_FALSE(
5872 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165873}
5874
mathpc992e602015-10-21 20:34:035875// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5876// reject HPKP headers, and a test setting only HPKP headers will fail (no
5877// PKPState present because header rejected).
5878#if defined(OS_ANDROID)
5879#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5880#define MAYBE_ProcessPKPAndSendReport DISABLED_ProcessPKPAndSendReport
5881#define MAYBE_ProcessPKPReportOnly DISABLED_ProcessPKPReportOnly
5882#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5883 DISABLED_ProcessPKPReportOnlyWithNoViolation
5884#else
5885#define MAYBE_ProcessPKP ProcessPKP
5886#define MAYBE_ProcessPKPAndSendReport ProcessPKPAndSendReport
5887#define MAYBE_ProcessPKPReportOnly ProcessPKPReportOnly
5888#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5889 ProcessPKPReportOnlyWithNoViolation
5890#endif
5891
estark06e0dac2015-08-07 21:56:015892namespace {
5893const char kHPKPReportUri[] = "https://hpkp-report.test";
5894} // namespace
5895
[email protected]37fd55fb2013-06-29 13:13:275896// Tests that enabling HPKP on a domain does not affect the HSTS
5897// validity/expiration.
mathpc992e602015-10-21 20:34:035898TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estark06e0dac2015-08-07 21:56:015899 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555900 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5901 https_test_server.SetSSLConfig(
5902 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5903 https_test_server.ServeFilesFromSourceDirectory(
5904 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275905 ASSERT_TRUE(https_test_server.Start());
5906
tommycli59a63432015-11-06 00:10:555907 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165908
[email protected]37fd55fb2013-06-29 13:13:275909 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195910 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555911 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195912 request->Start();
[email protected]255620da2013-08-19 13:14:295913 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275914 TransportSecurityState* security_state =
5915 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405916 TransportSecurityState::STSState sts_state;
5917 TransportSecurityState::PKPState pkp_state;
5918 EXPECT_FALSE(
5919 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5920 EXPECT_TRUE(
5921 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5922 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
5923 sts_state.upgrade_mode);
5924 EXPECT_FALSE(sts_state.include_subdomains);
5925 EXPECT_FALSE(pkp_state.include_subdomains);
5926 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:015927 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:405928 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:465929}
5930
estark06e0dac2015-08-07 21:56:015931// Tests that reports get sent on HPKP violations when a report-uri is set.
mathpc992e602015-10-21 20:34:035932TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:015933 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555934 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5935 https_test_server.SetSSLConfig(
5936 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5937 https_test_server.ServeFilesFromSourceDirectory(
5938 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015939 ASSERT_TRUE(https_test_server.Start());
5940
tommycli59a63432015-11-06 00:10:555941 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015942
5943 // Set up a pin for |test_server_hostname|.
5944 TransportSecurityState security_state;
5945 const base::Time current_time(base::Time::Now());
5946 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
5947 HashValueVector hashes;
5948 HashValue hash1;
5949 HashValue hash2;
5950 // The values here don't matter, as long as they are different from
5951 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:445952 ASSERT_TRUE(
5953 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
5954 ASSERT_TRUE(
5955 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:015956 hashes.push_back(hash1);
5957 hashes.push_back(hash2);
5958 security_state.AddHPKP(test_server_hostname, expiry,
5959 false, /* include subdomains */
5960 hashes, report_uri);
5961
5962 MockCertificateReportSender mock_report_sender;
5963 security_state.SetReportSender(&mock_report_sender);
5964
5965 // Set up a MockCertVerifier to trigger a violation of the previously
5966 // set pin.
5967 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5968 ASSERT_TRUE(cert);
5969
5970 MockCertVerifier cert_verifier;
5971 CertVerifyResult verify_result;
5972 verify_result.verified_cert = cert;
5973 verify_result.is_issued_by_known_root = true;
5974 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:445975 ASSERT_TRUE(
5976 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:015977 verify_result.public_key_hashes.push_back(hash3);
5978 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5979
5980 TestNetworkDelegate network_delegate;
5981 TestURLRequestContext context(true);
5982 context.set_transport_security_state(&security_state);
5983 context.set_network_delegate(&network_delegate);
5984 context.set_cert_verifier(&cert_verifier);
5985 context.Init();
5986
5987 // Now send a request to trigger the violation.
5988 TestDelegate d;
5989 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555990 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
estark06e0dac2015-08-07 21:56:015991 violating_request->Start();
5992 base::RunLoop().Run();
5993
5994 // Check that a report was sent.
5995 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5996 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5997 scoped_ptr<base::Value> value(
5998 base::JSONReader::Read(mock_report_sender.latest_report()));
5999 ASSERT_TRUE(value);
6000 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6001 base::DictionaryValue* report_dict;
6002 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6003 std::string report_hostname;
6004 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6005 EXPECT_EQ(test_server_hostname, report_hostname);
6006}
6007
6008// Tests that reports get sent on requests with
6009// Public-Key-Pins-Report-Only headers.
mathpc992e602015-10-21 20:34:036010TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016011 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556012 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6013 https_test_server.SetSSLConfig(
6014 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6015 https_test_server.ServeFilesFromSourceDirectory(
6016 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016017 ASSERT_TRUE(https_test_server.Start());
6018
tommycli59a63432015-11-06 00:10:556019 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016020
6021 TransportSecurityState security_state;
6022 MockCertificateReportSender mock_report_sender;
6023 security_state.SetReportSender(&mock_report_sender);
6024
6025 // Set up a MockCertVerifier to violate the pin in the Report-Only
6026 // header.
6027 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6028 ASSERT_TRUE(cert);
6029
6030 MockCertVerifier cert_verifier;
6031 CertVerifyResult verify_result;
6032 verify_result.verified_cert = cert;
6033 verify_result.is_issued_by_known_root = true;
6034 HashValue hash;
6035 // This value doesn't matter, as long as it is different from the pins
6036 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446037 ASSERT_TRUE(
6038 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016039 verify_result.public_key_hashes.push_back(hash);
6040 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6041
6042 TestNetworkDelegate network_delegate;
6043 TestURLRequestContext context(true);
6044 context.set_transport_security_state(&security_state);
6045 context.set_network_delegate(&network_delegate);
6046 context.set_cert_verifier(&cert_verifier);
6047 context.Init();
6048
6049 // Now send a request to trigger the violation.
6050 TestDelegate d;
6051 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556052 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016053 DEFAULT_PRIORITY, &d));
6054 violating_request->Start();
6055 base::RunLoop().Run();
6056
6057 // Check that a report was sent.
6058 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6059 ASSERT_FALSE(mock_report_sender.latest_report().empty());
6060 scoped_ptr<base::Value> value(
6061 base::JSONReader::Read(mock_report_sender.latest_report()));
6062 ASSERT_TRUE(value);
6063 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6064 base::DictionaryValue* report_dict;
6065 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6066 std::string report_hostname;
6067 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6068 EXPECT_EQ(test_server_hostname, report_hostname);
6069}
6070
6071// Tests that reports do not get sent on requests with
6072// Public-Key-Pins-Report-Only headers that don't have pin violations.
mathpc992e602015-10-21 20:34:036073TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016074 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556075 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6076 https_test_server.SetSSLConfig(
6077 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6078 https_test_server.ServeFilesFromSourceDirectory(
6079 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016080 ASSERT_TRUE(https_test_server.Start());
6081
tommycli59a63432015-11-06 00:10:556082 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016083
6084 TransportSecurityState security_state;
6085 MockCertificateReportSender mock_report_sender;
6086 security_state.SetReportSender(&mock_report_sender);
6087
6088 TestNetworkDelegate network_delegate;
6089 MockCertVerifier mock_cert_verifier;
6090 TestURLRequestContext context(true);
6091 context.set_transport_security_state(&security_state);
6092 context.set_network_delegate(&network_delegate);
6093 context.set_cert_verifier(&mock_cert_verifier);
6094 mock_cert_verifier.set_default_result(OK);
6095 context.Init();
6096
6097 // Now send a request that does not trigger the violation.
6098 TestDelegate d;
6099 scoped_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556100 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016101 DEFAULT_PRIORITY, &d));
6102 request->Start();
6103 base::RunLoop().Run();
6104
6105 // Check that a report was not sent.
6106 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6107 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6108}
6109
estarka5da76702015-04-09 04:00:166110TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556111 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6112 https_test_server.ServeFilesFromSourceDirectory(
6113 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166114 ASSERT_TRUE(https_test_server.Start());
6115 // Make sure this test fails if the test server is changed to not
6116 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556117 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6118 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166119
6120 TestDelegate d;
6121 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556122 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:166123 request->Start();
6124 base::RunLoop().Run();
6125
6126 TransportSecurityState* security_state =
6127 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406128 TransportSecurityState::PKPState pkp_state;
6129 EXPECT_FALSE(
6130 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166131}
6132
[email protected]242d8562012-10-30 21:20:466133TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556134 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6135 https_test_server.SetSSLConfig(
6136 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6137 https_test_server.ServeFilesFromSourceDirectory(
6138 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466139 ASSERT_TRUE(https_test_server.Start());
6140
tommycli59a63432015-11-06 00:10:556141 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166142
[email protected]242d8562012-10-30 21:20:466143 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196144 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556145 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
6146 &d));
[email protected]f7022f32014-08-21 16:32:196147 request->Start();
[email protected]255620da2013-08-19 13:14:296148 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466149
6150 // We should have set parameters from the first header, not the second.
6151 TransportSecurityState* security_state =
6152 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406153 TransportSecurityState::STSState sts_state;
6154 EXPECT_TRUE(
6155 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6156 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6157 sts_state.upgrade_mode);
6158 EXPECT_FALSE(sts_state.include_subdomains);
6159 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466160}
6161
[email protected]9f972ec2013-04-10 20:24:366162TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556163 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6164 https_test_server.SetSSLConfig(
6165 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6166 https_test_server.ServeFilesFromSourceDirectory(
6167 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366168 ASSERT_TRUE(https_test_server.Start());
6169
tommycli59a63432015-11-06 00:10:556170 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166171
[email protected]9f972ec2013-04-10 20:24:366172 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196173 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556174 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
6175 &d));
[email protected]f7022f32014-08-21 16:32:196176 request->Start();
[email protected]255620da2013-08-19 13:14:296177 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366178
6179 // We should have set parameters from the first header, not the second.
6180 TransportSecurityState* security_state =
6181 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406182 TransportSecurityState::STSState sts_state;
6183 TransportSecurityState::PKPState pkp_state;
6184 EXPECT_TRUE(
6185 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6186 EXPECT_TRUE(
6187 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6188 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6189 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036190#if defined(OS_ANDROID)
6191 // Android's CertVerifyProc does not (yet) handle pins.
6192#else
martijnc0d6b622015-06-30 19:14:406193 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036194#endif
martijnc0d6b622015-06-30 19:14:406195 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366196
[email protected]a165f092013-06-12 16:10:056197 // Even though there is an HSTS header asserting includeSubdomains, it is
6198 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406199 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056200 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406201 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366202}
6203
[email protected]37fd55fb2013-06-29 13:13:276204// Tests that when multiple HPKP headers are present, asserting different
6205// policies, that only the first such policy is processed.
6206TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556207 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6208 https_test_server.SetSSLConfig(
6209 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6210 https_test_server.ServeFilesFromSourceDirectory(
6211 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276212 ASSERT_TRUE(https_test_server.Start());
6213
tommycli59a63432015-11-06 00:10:556214 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166215
[email protected]37fd55fb2013-06-29 13:13:276216 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196217 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556218 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:366219 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196220 request->Start();
[email protected]255620da2013-08-19 13:14:296221 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276222
6223 TransportSecurityState* security_state =
6224 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406225 TransportSecurityState::STSState sts_state;
6226 TransportSecurityState::PKPState pkp_state;
6227 EXPECT_TRUE(
6228 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6229 EXPECT_TRUE(
6230 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6231 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6232 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036233#if defined(OS_ANDROID)
6234 // Android's CertVerifyProc does not (yet) handle pins.
6235#else
martijnc0d6b622015-06-30 19:14:406236 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036237#endif
martijnc0d6b622015-06-30 19:14:406238 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276239
martijnc0d6b622015-06-30 19:14:406240 EXPECT_TRUE(sts_state.include_subdomains);
6241 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276242}
6243
tommycli59a63432015-11-06 00:10:556244#endif // !defined(OS_IOS)
6245
[email protected]316c1e5e2012-09-12 15:17:446246TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:556247 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446248
6249 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196250 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556251 http_test_server()->GetURL("/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366252 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196253 req->Start();
[email protected]255620da2013-08-19 13:14:296254 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446255
6256 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196257 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446258 EXPECT_EQ("text/html", mime_type);
6259
6260 std::string charset;
[email protected]f7022f32014-08-21 16:32:196261 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446262 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196263 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446264}
6265
[email protected]02494ec2014-05-07 15:05:296266TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346267 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346268 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346269 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026270 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346271
6272 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506273 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346274}
6275
[email protected]02494ec2014-05-07 15:05:296276#if !defined(DISABLE_FILE_SUPPORT)
6277TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6278 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6279 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456280 FileProtocolHandler file_protocol_handler(
6281 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296282 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6283
6284 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506285 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296286}
6287
[email protected]588614c22013-08-16 00:09:026288TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:556289 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446290
6291 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196292 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556293 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366294 &d));
[email protected]f7022f32014-08-21 16:32:196295 req->Start();
[email protected]255620da2013-08-19 13:14:296296 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446297
[email protected]f7022f32014-08-21 16:32:196298 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6299 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446300}
[email protected]02494ec2014-05-07 15:05:296301#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446302
[email protected]588614c22013-08-16 00:09:026303TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:556304 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:026305
6306 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196307 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556308 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366309 &d));
[email protected]f7022f32014-08-21 16:32:196310 req->Start();
[email protected]588614c22013-08-16 00:09:026311 base::MessageLoop::current()->Run();
6312
[email protected]f7022f32014-08-21 16:32:196313 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6314 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:026315}
6316
[email protected]316c1e5e2012-09-12 15:17:446317TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:556318 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446319
6320 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196321 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556322 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366323 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196324 req->Start();
[email protected]255620da2013-08-19 13:14:296325 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446326
[email protected]f7022f32014-08-21 16:32:196327 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6328 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446329}
6330
[email protected]e50efea2014-03-24 18:41:006331// Make sure redirects are cached, despite not reading their bodies.
6332TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:556333 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006334 GURL redirect_url =
tommycli59a63432015-11-06 00:10:556335 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:006336
6337 {
6338 TestDelegate d;
davidben151423e2015-03-23 18:48:366339 scoped_ptr<URLRequest> req(
6340 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196341 req->Start();
[email protected]e50efea2014-03-24 18:41:006342 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196343 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006344 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:556345 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006346 }
6347
6348 {
6349 TestDelegate d;
6350 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:366351 scoped_ptr<URLRequest> req(
6352 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196353 req->Start();
[email protected]e50efea2014-03-24 18:41:006354 base::RunLoop().Run();
6355
6356 EXPECT_EQ(1, d.received_redirect_count());
6357 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196358 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006359
[email protected]f7022f32014-08-21 16:32:196360 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006361 base::RunLoop().Run();
6362 EXPECT_EQ(1, d.received_redirect_count());
6363 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196364 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
tommycli59a63432015-11-06 00:10:556365 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006366 }
6367}
6368
6369// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6370// when the headers are read, since the body won't have been read.
6371TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:556372 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006373 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:556374 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:006375
6376 {
6377 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:556378 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:006379 default_network_delegate_.set_redirect_on_headers_received_url(
6380 redirect_to_url);
6381
6382 TestDelegate d;
davidben151423e2015-03-23 18:48:366383 scoped_ptr<URLRequest> req(
6384 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196385 req->Start();
[email protected]e50efea2014-03-24 18:41:006386 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196387 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006388 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196389 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006390 }
6391
6392 {
6393 TestDelegate d;
davidben151423e2015-03-23 18:48:366394 scoped_ptr<URLRequest> req(
6395 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196396 req->Start();
[email protected]e50efea2014-03-24 18:41:006397 base::RunLoop().Run();
6398
[email protected]f7022f32014-08-21 16:32:196399 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6400 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006401 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196402 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006403 }
6404}
6405
[email protected]5f714132014-03-26 10:41:166406// Tests that redirection to an unsafe URL is allowed when it has been marked as
6407// safe.
6408TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:556409 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166410
6411 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6412 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6413 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6414
6415 TestDelegate d;
6416 {
[email protected]f7022f32014-08-21 16:32:196417 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556418 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166419
[email protected]f7022f32014-08-21 16:32:196420 r->Start();
[email protected]5f714132014-03-26 10:41:166421 base::RunLoop().Run();
6422
[email protected]f7022f32014-08-21 16:32:196423 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:166424
[email protected]f7022f32014-08-21 16:32:196425 EXPECT_EQ(2U, r->url_chain().size());
6426 EXPECT_EQ(OK, r->status().error());
6427 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166428 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6429 }
6430}
6431
6432// Tests that a redirect to a different unsafe URL is blocked, even after adding
6433// some other URL to the whitelist.
6434TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:556435 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166436
6437 GURL unsafe_url("data:text/html,something");
6438 GURL different_unsafe_url("data:text/html,something-else");
6439 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6440 default_network_delegate_.set_allowed_unsafe_redirect_url(
6441 different_unsafe_url);
6442
6443 TestDelegate d;
6444 {
[email protected]f7022f32014-08-21 16:32:196445 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556446 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166447
[email protected]f7022f32014-08-21 16:32:196448 r->Start();
[email protected]5f714132014-03-26 10:41:166449 base::RunLoop().Run();
6450
[email protected]f7022f32014-08-21 16:32:196451 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
6452 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:166453 }
6454}
6455
[email protected]5f714132014-03-26 10:41:166456// Redirects from an URL with fragment to an unsafe URL with fragment should
6457// be allowed, and the reference fragment of the target URL should be preserved.
6458TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:556459 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166460
tommycli59a63432015-11-06 00:10:556461 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:166462 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6463 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6464
6465 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6466 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6467
6468 TestDelegate d;
6469 {
davidben151423e2015-03-23 18:48:366470 scoped_ptr<URLRequest> r(
6471 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166472
[email protected]f7022f32014-08-21 16:32:196473 r->Start();
[email protected]5f714132014-03-26 10:41:166474 base::RunLoop().Run();
6475
[email protected]f7022f32014-08-21 16:32:196476 EXPECT_EQ(2U, r->url_chain().size());
6477 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6478 EXPECT_EQ(OK, r->status().error());
6479 EXPECT_EQ(original_url, r->original_url());
6480 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166481 }
6482}
6483
6484// When a delegate has specified a safe redirect URL, but it does not match the
6485// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146486TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:556487 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166488
tommycli59a63432015-11-06 00:10:556489 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166490 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:556491 GURL redirect_url(http_test_server()->GetURL("/target"));
6492 GURL expected_redirect_url(
6493 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166494
6495 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6496 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6497
6498 TestDelegate d;
6499 {
davidben151423e2015-03-23 18:48:366500 scoped_ptr<URLRequest> r(
6501 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166502
[email protected]f7022f32014-08-21 16:32:196503 r->Start();
[email protected]5f714132014-03-26 10:41:166504 base::RunLoop().Run();
6505
[email protected]f7022f32014-08-21 16:32:196506 EXPECT_EQ(2U, r->url_chain().size());
6507 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6508 EXPECT_EQ(OK, r->status().error());
6509 EXPECT_EQ(original_url, r->original_url());
6510 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166511 }
6512}
6513
[email protected]f878230e2014-04-03 15:36:146514// When a delegate has specified a safe redirect URL, assume that the redirect
6515// URL should not be changed. In particular, the reference fragment should not
6516// be modified.
6517TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556518 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146519
tommycli59a63432015-11-06 00:10:556520 GURL original_url(
6521 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:146522 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6523
6524 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6525 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6526
6527 TestDelegate d;
6528 {
davidben151423e2015-03-23 18:48:366529 scoped_ptr<URLRequest> r(
6530 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146531
[email protected]f7022f32014-08-21 16:32:196532 r->Start();
[email protected]f878230e2014-04-03 15:36:146533 base::RunLoop().Run();
6534
[email protected]f7022f32014-08-21 16:32:196535 EXPECT_EQ(2U, r->url_chain().size());
6536 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6537 EXPECT_EQ(OK, r->status().error());
6538 EXPECT_EQ(original_url, r->original_url());
6539 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146540 }
6541}
6542
6543// When a URLRequestRedirectJob is created, the redirection must be followed and
6544// the reference fragment of the target URL must not be modified.
6545TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556546 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146547
tommycli59a63432015-11-06 00:10:556548 GURL original_url(
6549 http_test_server()->GetURL("/original#should-not-be-appended"));
6550 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:146551
6552 TestDelegate d;
davidben151423e2015-03-23 18:48:366553 scoped_ptr<URLRequest> r(
6554 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146555
mmenkeed0498b2015-12-08 23:20:426556 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196557 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:426558 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
6559 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:146560
[email protected]f7022f32014-08-21 16:32:196561 r->Start();
[email protected]f878230e2014-04-03 15:36:146562 base::RunLoop().Run();
6563
[email protected]f7022f32014-08-21 16:32:196564 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6565 EXPECT_EQ(OK, r->status().error());
6566 EXPECT_EQ(original_url, r->original_url());
6567 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146568}
6569
lizeb5120f6dc2016-02-19 09:29:446570TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
6571 ASSERT_TRUE(http_test_server()->Start());
6572
6573 const std::string referrer("foobar://totally.legit.referrer");
6574 TestDelegate d;
6575 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6576 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
6577 req->SetReferrer(referrer);
6578 req->Start();
6579 base::RunLoop().Run();
6580
6581 EXPECT_EQ(std::string("None"), d.data_received());
6582}
6583
[email protected]316c1e5e2012-09-12 15:17:446584TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:556585 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446586
6587 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196588 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556589 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196590 req->SetReferrer("http://user:[email protected]/");
6591 req->Start();
[email protected]255620da2013-08-19 13:14:296592 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446593
6594 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6595}
6596
[email protected]99ecf6e2013-04-10 22:46:136597TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:556598 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136599
6600 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196601 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556602 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196603 req->SetReferrer("http://foo.com/test#fragment");
6604 req->Start();
[email protected]255620da2013-08-19 13:14:296605 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136606
6607 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6608}
6609
6610TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:556611 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136612
6613 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196614 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556615 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196616 req->SetReferrer("http://foo.com/test#fragment");
6617 req->SetReferrer("");
6618 req->Start();
[email protected]255620da2013-08-19 13:14:296619 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136620
6621 EXPECT_EQ(std::string("None"), d.data_received());
6622}
6623
[email protected]1826a402014-01-08 15:40:486624// Defer network start and then resume, checking that the request was a success
6625// and bytes were received.
6626TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556627 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486628
6629 TestDelegate d;
6630 {
6631 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556632 GURL test_url(http_test_server()->GetURL("/echo"));
davidben151423e2015-03-23 18:48:366633 scoped_ptr<URLRequest> req(
6634 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486635
[email protected]f7022f32014-08-21 16:32:196636 req->Start();
[email protected]1826a402014-01-08 15:40:486637 base::RunLoop().Run();
6638
6639 EXPECT_EQ(1, d.received_before_network_start_count());
6640 EXPECT_EQ(0, d.response_started_count());
6641
[email protected]f7022f32014-08-21 16:32:196642 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486643 base::RunLoop().Run();
6644
6645 EXPECT_EQ(1, d.response_started_count());
6646 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196647 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486648 }
6649}
6650
6651// Check that OnBeforeNetworkStart is only called once even if there is a
6652// redirect.
6653TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
tommycli59a63432015-11-06 00:10:556654 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486655
6656 TestDelegate d;
6657 {
6658 d.set_quit_on_redirect(true);
6659 d.set_quit_on_network_start(true);
[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("/server-redirect?echo"), DEFAULT_PRIORITY,
6662 &d));
[email protected]1826a402014-01-08 15:40:486663
[email protected]f7022f32014-08-21 16:32:196664 req->Start();
[email protected]1826a402014-01-08 15:40:486665 base::RunLoop().Run();
6666
6667 EXPECT_EQ(1, d.received_before_network_start_count());
6668 EXPECT_EQ(0, d.response_started_count());
6669 EXPECT_EQ(0, d.received_redirect_count());
6670
[email protected]f7022f32014-08-21 16:32:196671 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486672 base::RunLoop().Run();
6673
6674 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196675 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:486676 base::RunLoop().Run();
6677
6678 // Check that the redirect's new network transaction does not get propagated
6679 // to a second OnBeforeNetworkStart() notification.
6680 EXPECT_EQ(1, d.received_before_network_start_count());
6681
6682 EXPECT_EQ(1, d.response_started_count());
6683 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196684 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486685 }
6686}
6687
6688// Cancel the request after learning that the request would use the network.
6689TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556690 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486691
6692 TestDelegate d;
6693 {
6694 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556695 GURL test_url(http_test_server()->GetURL("/echo"));
davidben151423e2015-03-23 18:48:366696 scoped_ptr<URLRequest> req(
6697 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486698
[email protected]f7022f32014-08-21 16:32:196699 req->Start();
[email protected]1826a402014-01-08 15:40:486700 base::RunLoop().Run();
6701
6702 EXPECT_EQ(1, d.received_before_network_start_count());
6703 EXPECT_EQ(0, d.response_started_count());
6704
[email protected]f7022f32014-08-21 16:32:196705 req->Cancel();
[email protected]1826a402014-01-08 15:40:486706 base::RunLoop().Run();
6707
6708 EXPECT_EQ(1, d.response_started_count());
6709 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196710 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:486711 }
6712}
6713
[email protected]316c1e5e2012-09-12 15:17:446714TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:556715 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446716
6717 TestDelegate d;
6718 {
6719 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:196720 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556721 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6722 &d));
[email protected]f7022f32014-08-21 16:32:196723 req->Start();
[email protected]255620da2013-08-19 13:14:296724 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446725
6726 EXPECT_EQ(1, d.response_started_count());
6727 EXPECT_EQ(0, d.bytes_received());
6728 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196729 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446730 }
6731}
6732
6733TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:556734 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446735
6736 TestDelegate d;
6737 {
6738 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556739 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
davidben151423e2015-03-23 18:48:366740 scoped_ptr<URLRequest> req(
6741 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046742
[email protected]f7022f32014-08-21 16:32:196743 req->Start();
[email protected]255620da2013-08-19 13:14:296744 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446745
6746 EXPECT_EQ(1, d.received_redirect_count());
6747
[email protected]f7022f32014-08-21 16:32:196748 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296749 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446750
6751 EXPECT_EQ(1, d.response_started_count());
6752 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196753 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446754
[email protected]6cdfd7f2013-02-08 20:40:156755 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446756 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476757 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446758 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6759
6760 std::string contents;
[email protected]82f84b92013-08-30 18:23:506761 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446762 EXPECT_EQ(contents, d.data_received());
6763 }
6764}
6765
[email protected]79e1fd62013-06-20 06:50:046766TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:556767 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:046768
6769 TestDelegate d;
6770 {
6771 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556772 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
davidben151423e2015-03-23 18:48:366773 scoped_ptr<URLRequest> req(
6774 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046775
6776 EXPECT_FALSE(d.have_full_request_headers());
6777
[email protected]f7022f32014-08-21 16:32:196778 req->Start();
[email protected]255620da2013-08-19 13:14:296779 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046780
6781 EXPECT_EQ(1, d.received_redirect_count());
6782 EXPECT_TRUE(d.have_full_request_headers());
6783 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6784 d.ClearFullRequestHeaders();
6785
[email protected]f7022f32014-08-21 16:32:196786 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296787 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046788
tommycli59a63432015-11-06 00:10:556789 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:046790 EXPECT_EQ(1, d.response_started_count());
6791 EXPECT_TRUE(d.have_full_request_headers());
6792 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6793 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196794 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046795
6796 base::FilePath path;
6797 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476798 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046799 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6800
6801 std::string contents;
[email protected]82f84b92013-08-30 18:23:506802 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046803 EXPECT_EQ(contents, d.data_received());
6804 }
6805}
6806
[email protected]316c1e5e2012-09-12 15:17:446807TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:556808 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446809
6810 TestDelegate d;
6811 {
6812 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196813 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556814 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6815 &d));
[email protected]f7022f32014-08-21 16:32:196816 req->Start();
[email protected]255620da2013-08-19 13:14:296817 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446818
6819 EXPECT_EQ(1, d.received_redirect_count());
6820
[email protected]f7022f32014-08-21 16:32:196821 req->Cancel();
[email protected]255620da2013-08-19 13:14:296822 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446823
6824 EXPECT_EQ(1, d.response_started_count());
6825 EXPECT_EQ(0, d.bytes_received());
6826 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196827 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446828 }
6829}
6830
6831TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:556832 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446833
[email protected]3b23a222013-05-15 21:33:256834 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446835 {
6836 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196837 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556838 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6839 &d));
[email protected]316c1e5e2012-09-12 15:17:446840 HttpRequestHeaders headers;
6841 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196842 req->SetExtraRequestHeaders(headers);
6843 req->Start();
[email protected]255620da2013-08-19 13:14:296844 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256845
6846 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196847 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256848 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446849 }
6850
[email protected]3b23a222013-05-15 21:33:256851 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446852 {
6853 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196854 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556855 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6856 &d));
[email protected]316c1e5e2012-09-12 15:17:446857 HttpRequestHeaders headers;
6858 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196859 req->SetExtraRequestHeaders(headers);
6860 req->Start();
[email protected]255620da2013-08-19 13:14:296861 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446862
[email protected]f7022f32014-08-21 16:32:196863 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256864
6865 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196866 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256867 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446868 }
6869
[email protected]3b23a222013-05-15 21:33:256870 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446871 {
6872 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196873 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556874 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6875 &d));
[email protected]316c1e5e2012-09-12 15:17:446876 HttpRequestHeaders headers;
6877 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196878 req->SetExtraRequestHeaders(headers);
6879 req->Start();
[email protected]255620da2013-08-19 13:14:296880 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446881
[email protected]f7022f32014-08-21 16:32:196882 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256883
6884 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196885 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256886 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446887 }
6888}
6889
6890TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:556891 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446892
6893 // populate the cache
6894 {
6895 TestDelegate d;
6896 d.set_credentials(AuthCredentials(kUser, kSecret));
6897
[email protected]f7022f32014-08-21 16:32:196898 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556899 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196900 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446901
[email protected]255620da2013-08-19 13:14:296902 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446903
6904 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6905 }
6906
6907 // repeat request with end-to-end validation. since auth-basic results in a
6908 // cachable page, we expect this test to result in a 304. in which case, the
6909 // response should be fetched from the cache.
6910 {
6911 TestDelegate d;
6912 d.set_credentials(AuthCredentials(kUser, kSecret));
6913
[email protected]f7022f32014-08-21 16:32:196914 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556915 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196916 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6917 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446918
[email protected]255620da2013-08-19 13:14:296919 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446920
6921 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6922
6923 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196924 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446925 }
6926}
6927
6928// Check that Set-Cookie headers in 401 responses are respected.
6929// http://crbug.com/6450
6930TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:556931 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446932
6933 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:556934 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:446935
6936 // Request a page that will give a 401 containing a Set-Cookie header.
6937 // Verify that when the transaction is restarted, it includes the new cookie.
6938 {
[email protected]ceefd7fd2012-11-29 00:36:246939 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446940 TestURLRequestContext context(true);
6941 context.set_network_delegate(&network_delegate);
6942 context.Init();
6943
6944 TestDelegate d;
6945 d.set_credentials(AuthCredentials(kUser, kSecret));
6946
davidben151423e2015-03-23 18:48:366947 scoped_ptr<URLRequest> r(
6948 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196949 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446950
[email protected]255620da2013-08-19 13:14:296951 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446952
6953 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6954
6955 // Make sure we sent the cookie in the restarted transaction.
6956 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6957 != std::string::npos);
6958 }
6959
6960 // Same test as above, except this time the restart is initiated earlier
6961 // (without user intervention since identity is embedded in the URL).
6962 {
[email protected]ceefd7fd2012-11-29 00:36:246963 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446964 TestURLRequestContext context(true);
6965 context.set_network_delegate(&network_delegate);
6966 context.Init();
6967
6968 TestDelegate d;
6969
6970 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186971 replacements.SetUsernameStr("user2");
6972 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446973 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6974
davidben151423e2015-03-23 18:48:366975 scoped_ptr<URLRequest> r(
6976 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196977 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446978
[email protected]255620da2013-08-19 13:14:296979 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446980
6981 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6982
6983 // Make sure we sent the cookie in the restarted transaction.
6984 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6985 != std::string::npos);
6986 }
6987}
6988
[email protected]58e32bb2013-01-21 18:23:256989// Tests that load timing works as expected with auth and the cache.
6990TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:556991 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:256992
6993 // populate the cache
6994 {
6995 TestDelegate d;
6996 d.set_credentials(AuthCredentials(kUser, kSecret));
6997
[email protected]f7022f32014-08-21 16:32:196998 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556999 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197000 r->Start();
[email protected]58e32bb2013-01-21 18:23:257001
[email protected]255620da2013-08-19 13:14:297002 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257003
7004 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7005
7006 LoadTimingInfo load_timing_info_before_auth;
7007 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
7008 &load_timing_info_before_auth));
7009 TestLoadTimingNotReused(load_timing_info_before_auth,
7010 CONNECT_TIMING_HAS_DNS_TIMES);
7011
7012 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197013 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257014 // The test server does not support keep alive sockets, so the second
7015 // request with auth should use a new socket.
7016 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7017 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7018 load_timing_info.socket_log_id);
7019 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7020 load_timing_info.connect_timing.connect_start);
7021 }
7022
[email protected]3b23a222013-05-15 21:33:257023 // Repeat request with end-to-end validation. Since auth-basic results in a
7024 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:257025 // response should be fetched from the cache.
7026 {
7027 TestDelegate d;
7028 d.set_credentials(AuthCredentials(kUser, kSecret));
7029
[email protected]f7022f32014-08-21 16:32:197030 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557031 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197032 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7033 r->Start();
[email protected]58e32bb2013-01-21 18:23:257034
[email protected]255620da2013-08-19 13:14:297035 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257036
7037 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7038
7039 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197040 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:257041
[email protected]3b23a222013-05-15 21:33:257042 // Since there was a request that went over the wire, the load timing
7043 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:257044 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197045 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257046 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:257047 }
7048}
7049
[email protected]316c1e5e2012-09-12 15:17:447050// In this test, we do a POST which the server will 302 redirect.
7051// The subsequent transaction should use GET, and should not send the
7052// Content-Type header.
7053// http://code.google.com/p/chromium/issues/detail?id=843
7054TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:557055 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447056
7057 const char kData[] = "hello world";
7058
7059 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197060 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557061 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY,
7062 &d));
[email protected]f7022f32014-08-21 16:32:197063 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077064 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447065
7066 // Set headers (some of which are specific to the POST).
7067 HttpRequestHeaders headers;
7068 headers.AddHeadersFromString(
7069 "Content-Type: multipart/form-data; "
7070 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
7071 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
7072 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
7073 "Accept-Language: en-US,en\r\n"
7074 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
7075 "Content-Length: 11\r\n"
7076 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:197077 req->SetExtraRequestHeaders(headers);
7078 req->Start();
[email protected]255620da2013-08-19 13:14:297079 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447080
7081 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197082 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447083 EXPECT_EQ("text/html", mime_type);
7084
7085 const std::string& data = d.data_received();
7086
7087 // Check that the post-specific headers were stripped:
7088 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
7089 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
7090 EXPECT_FALSE(ContainsString(data, "Origin:"));
7091
7092 // These extra request headers should not have been stripped.
7093 EXPECT_TRUE(ContainsString(data, "Accept:"));
7094 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
7095 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
7096}
7097
jww5fe460ff2015-03-28 00:22:517098// The following tests check that we handle mutating the request for HTTP
7099// redirects as expected.
7100// See https://crbug.com/56373, https://crbug.com/102130, and
7101// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:447102
7103TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:557104 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447105
tommycli59a63432015-11-06 00:10:557106 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:517107 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557108 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:447109
7110 HTTPRedirectMethodTest(url, "POST", "GET", true);
7111 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7112 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517113
7114 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7115 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7116 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7117 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7118 std::string());
[email protected]316c1e5e2012-09-12 15:17:447119}
7120
7121TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:557122 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447123
tommycli59a63432015-11-06 00:10:557124 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:517125 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557126 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:447127
7128 HTTPRedirectMethodTest(url, "POST", "GET", true);
7129 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7130 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517131
7132 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7133 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7134 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7135 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7136 std::string());
[email protected]316c1e5e2012-09-12 15:17:447137}
7138
7139TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:557140 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447141
tommycli59a63432015-11-06 00:10:557142 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:517143 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557144 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:447145
7146 HTTPRedirectMethodTest(url, "POST", "GET", true);
7147 HTTPRedirectMethodTest(url, "PUT", "GET", true);
7148 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517149
7150 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7151 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7152 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7153 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7154 std::string());
[email protected]316c1e5e2012-09-12 15:17:447155}
7156
7157TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:557158 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447159
tommycli59a63432015-11-06 00:10:557160 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:517161 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557162 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:447163
7164 HTTPRedirectMethodTest(url, "POST", "POST", true);
7165 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7166 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517167
7168 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7169 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7170 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7171 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:447172}
7173
[email protected]0a17aab32014-04-24 03:32:377174TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:557175 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377176
tommycli59a63432015-11-06 00:10:557177 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:517178 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557179 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:377180
7181 HTTPRedirectMethodTest(url, "POST", "POST", true);
7182 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7183 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517184
7185 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7186 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7187 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7188 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:377189}
7190
7191// Make sure that 308 responses without bodies are not treated as redirects.
7192// Certain legacy apis that pre-date the response code expect this behavior
7193// (Like Google Drive).
7194TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:557195 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377196
7197 TestDelegate d;
tommycli59a63432015-11-06 00:10:557198 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:377199
davidben151423e2015-03-23 18:48:367200 scoped_ptr<URLRequest> request(
7201 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:377202
[email protected]f7022f32014-08-21 16:32:197203 request->Start();
[email protected]0a17aab32014-04-24 03:32:377204 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197205 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
7206 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:377207 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197208 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:377209 EXPECT_EQ("This is not a redirect.", d.data_received());
7210}
7211
[email protected]f878230e2014-04-03 15:36:147212TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:557213 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147214
tommycli59a63432015-11-06 00:10:557215 GURL original_url(
7216 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
7217 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:147218
7219 TestDelegate d;
7220 {
davidben151423e2015-03-23 18:48:367221 scoped_ptr<URLRequest> r(
7222 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:147223
[email protected]f7022f32014-08-21 16:32:197224 r->Start();
[email protected]f878230e2014-04-03 15:36:147225 base::RunLoop().Run();
7226
[email protected]f7022f32014-08-21 16:32:197227 EXPECT_EQ(2U, r->url_chain().size());
7228 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7229 EXPECT_EQ(OK, r->status().error());
7230 EXPECT_EQ(original_url, r->original_url());
7231 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:147232 }
7233}
7234
[email protected]cba24642014-08-15 20:49:597235TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557236 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597237
tommycli59a63432015-11-06 00:10:557238 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597239 GURL first_party_url("http://example.com");
7240
7241 TestDelegate d;
7242 {
davidben151423e2015-03-23 18:48:367243 scoped_ptr<URLRequest> r(
7244 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197245 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:597246
[email protected]f7022f32014-08-21 16:32:197247 r->Start();
[email protected]cba24642014-08-15 20:49:597248 base::RunLoop().Run();
7249
[email protected]f7022f32014-08-21 16:32:197250 EXPECT_EQ(2U, r->url_chain().size());
7251 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7252 EXPECT_EQ(OK, r->status().error());
7253 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597254 }
7255}
7256
7257TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557258 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597259
tommycli59a63432015-11-06 00:10:557260 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597261 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:557262 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:597263
7264 TestDelegate d;
7265 {
davidben151423e2015-03-23 18:48:367266 scoped_ptr<URLRequest> r(
7267 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197268 r->set_first_party_for_cookies(original_first_party_url);
7269 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597270 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7271
[email protected]f7022f32014-08-21 16:32:197272 r->Start();
[email protected]cba24642014-08-15 20:49:597273 base::RunLoop().Run();
7274
[email protected]f7022f32014-08-21 16:32:197275 EXPECT_EQ(2U, r->url_chain().size());
7276 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7277 EXPECT_EQ(OK, r->status().error());
7278 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597279 }
7280}
7281
[email protected]316c1e5e2012-09-12 15:17:447282TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:557283 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447284
7285 const char kData[] = "hello world";
7286
7287 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197288 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557289 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197290 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077291 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447292 HttpRequestHeaders headers;
7293 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517294 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197295 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447296
mmenkeed0498b2015-12-08 23:20:427297 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557298 req.get(), &default_network_delegate_,
7299 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427300 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7301 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447302
[email protected]f7022f32014-08-21 16:32:197303 req->Start();
[email protected]255620da2013-08-19 13:14:297304 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197305 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447306}
7307
7308TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:557309 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447310
7311 const char kData[] = "hello world";
7312
7313 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197314 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557315 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197316 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077317 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447318 HttpRequestHeaders headers;
7319 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517320 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197321 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447322
mmenkeed0498b2015-12-08 23:20:427323 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557324 req.get(), &default_network_delegate_,
7325 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097326 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:427327 "Very Good Reason"));
7328 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447329
[email protected]f7022f32014-08-21 16:32:197330 req->Start();
[email protected]255620da2013-08-19 13:14:297331 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197332 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447333 EXPECT_EQ(kData, d.data_received());
7334}
7335
7336// Check that default A-L header is sent.
7337TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557338 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447339
[email protected]8790210c2013-12-02 05:29:537340 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247341 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447342 TestURLRequestContext context(true);
7343 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437344 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447345 context.Init();
7346
7347 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197348 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557349 http_test_server()->GetURL("/echoheader?Accept-Language"),
7350 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197351 req->Start();
[email protected]255620da2013-08-19 13:14:297352 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447353 EXPECT_EQ("en", d.data_received());
7354}
7355
7356// Check that an empty A-L header is not sent. http://crbug.com/77365.
7357TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557358 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447359
[email protected]8790210c2013-12-02 05:29:537360 std::string empty_string; // Avoid most vexing parse on line below.
7361 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247362 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447363 TestURLRequestContext context(true);
7364 context.set_network_delegate(&network_delegate);
7365 context.Init();
7366 // We override the language after initialization because empty entries
7367 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437368 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447369
7370 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197371 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557372 http_test_server()->GetURL("/echoheader?Accept-Language"),
7373 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197374 req->Start();
[email protected]255620da2013-08-19 13:14:297375 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447376 EXPECT_EQ("None", d.data_received());
7377}
7378
7379// Check that if request overrides the A-L header, the default is not appended.
7380// See http://crbug.com/20894
7381TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557382 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447383
7384 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197385 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557386 http_test_server()->GetURL("/echoheader?Accept-Language"),
7387 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447388 HttpRequestHeaders headers;
7389 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197390 req->SetExtraRequestHeaders(headers);
7391 req->Start();
[email protected]255620da2013-08-19 13:14:297392 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447393 EXPECT_EQ(std::string("ru"), d.data_received());
7394}
7395
7396// Check that default A-E header is sent.
7397TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557398 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447399
7400 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197401 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557402 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7403 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447404 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197405 req->SetExtraRequestHeaders(headers);
7406 req->Start();
[email protected]255620da2013-08-19 13:14:297407 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447408 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7409}
7410
7411// Check that if request overrides the A-E header, the default is not appended.
7412// See http://crbug.com/47381
7413TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557414 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447415
7416 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197417 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557418 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7419 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447420 HttpRequestHeaders headers;
7421 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197422 req->SetExtraRequestHeaders(headers);
7423 req->Start();
[email protected]255620da2013-08-19 13:14:297424 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447425 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7426 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7427}
7428
[email protected]84f05432013-03-15 01:00:127429// Check that setting the A-C header sends the proper header.
7430TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:557431 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447432
7433 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197434 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557435 http_test_server()->GetURL("/echoheader?Accept-Charset"),
7436 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447437 HttpRequestHeaders headers;
7438 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197439 req->SetExtraRequestHeaders(headers);
7440 req->Start();
[email protected]255620da2013-08-19 13:14:297441 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447442 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7443}
7444
7445// Check that default User-Agent header is sent.
7446TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:557447 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447448
7449 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197450 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557451 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7452 &d));
[email protected]f7022f32014-08-21 16:32:197453 req->Start();
[email protected]255620da2013-08-19 13:14:297454 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197455 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377456 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447457}
7458
7459// Check that if request overrides the User-Agent header,
7460// the default is not appended.
marqf14fff8d2015-12-02 15:52:297461// TODO(crbug.com/564656) This test is flaky on iOS.
7462#if defined(OS_IOS)
7463#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
7464#else
7465#define MAYBE_OverrideUserAgent OverrideUserAgent
7466#endif
7467TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:557468 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447469
7470 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197471 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557472 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7473 &d));
[email protected]316c1e5e2012-09-12 15:17:447474 HttpRequestHeaders headers;
7475 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197476 req->SetExtraRequestHeaders(headers);
7477 req->Start();
[email protected]255620da2013-08-19 13:14:297478 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357479 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447480}
7481
[email protected]ee4c30d2012-11-07 15:08:437482// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7483// User-Agent header to be sent but does not send the Accept-Language and
7484// Accept-Charset headers.
7485TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:557486 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:437487
[email protected]ceefd7fd2012-11-29 00:36:247488 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437489 TestURLRequestContext context(true);
7490 context.set_network_delegate(&network_delegate);
7491 context.Init();
7492 // We override the HttpUserAgentSettings after initialization because empty
7493 // entries get overridden by Init().
7494 context.set_http_user_agent_settings(NULL);
7495
7496 struct {
7497 const char* request;
7498 const char* expected_response;
tommycli59a63432015-11-06 00:10:557499 } tests[] = {{"/echoheader?Accept-Language", "None"},
7500 {"/echoheader?Accept-Charset", "None"},
7501 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:437502
viettrungluue4a8b882014-10-16 06:17:387503 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437504 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197505 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557506 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197507 req->Start();
[email protected]255620da2013-08-19 13:14:297508 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437509 EXPECT_EQ(tests[i].expected_response, d.data_received())
7510 << " Request = \"" << tests[i].request << "\"";
7511 }
7512}
7513
[email protected]5033ab82013-03-22 20:17:467514// Make sure that URLRequest passes on its priority updates to
7515// newly-created jobs after the first one.
7516TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:557517 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:467518
7519 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197520 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557521 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197522 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467523
mmenkeed0498b2015-12-08 23:20:427524 scoped_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557525 req.get(), &default_network_delegate_,
7526 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427527 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7528 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:467529
[email protected]f7022f32014-08-21 16:32:197530 req->SetPriority(LOW);
7531 req->Start();
7532 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467533
mmenkeed0498b2015-12-08 23:20:427534 RequestPriority job_priority;
7535 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
7536 req.get(), &default_network_delegate_, &job_priority));
7537 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:467538
7539 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297540 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:427541 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:467542}
7543
[email protected]80abdad2014-03-15 00:20:547544// Check that creating a network request while entering/exiting suspend mode
7545// fails as it should. This is the only case where an HttpTransactionFactory
7546// does not return an HttpTransaction.
7547TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7548 // Create a new HttpNetworkLayer that thinks it's suspended.
mmenke2281f3762015-11-02 20:38:177549 scoped_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
7550 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547551 network_layer->OnSuspend();
7552
dchengc7eeda422015-12-26 03:56:487553 HttpCache http_cache(std::move(network_layer),
mmenkee65e7af2015-10-13 17:16:427554 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547555
7556 TestURLRequestContext context(true);
7557 context.set_http_transaction_factory(&http_cache);
7558 context.Init();
7559
7560 TestDelegate d;
davidben151423e2015-03-23 18:48:367561 scoped_ptr<URLRequest> req(
7562 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197563 req->Start();
[email protected]80abdad2014-03-15 00:20:547564 base::RunLoop().Run();
7565
7566 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197567 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7568 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547569}
7570
mmenke2281f3762015-11-02 20:38:177571namespace {
[email protected]80abdad2014-03-15 00:20:547572
mmenke2281f3762015-11-02 20:38:177573// HttpTransactionFactory that synchronously fails to create transactions.
7574class FailingHttpTransactionFactory : public HttpTransactionFactory {
7575 public:
7576 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7577 : network_session_(network_session) {}
7578
7579 ~FailingHttpTransactionFactory() override {}
7580
7581 // HttpTransactionFactory methods:
7582 int CreateTransaction(RequestPriority priority,
7583 scoped_ptr<HttpTransaction>* trans) override {
7584 return ERR_FAILED;
7585 }
7586
7587 HttpCache* GetCache() override { return nullptr; }
7588
7589 HttpNetworkSession* GetSession() override { return network_session_; }
7590
7591 private:
7592 HttpNetworkSession* network_session_;
7593
7594 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7595};
7596
7597} // namespace
7598
7599// Check that when a request that fails to create an HttpTransaction can be
7600// cancelled while the failure notification is pending, and doesn't send two
7601// failure notifications.
7602//
7603// This currently only happens when in suspend mode and there's no cache, but
7604// just use a special HttpTransactionFactory, to avoid depending on those
7605// behaviors.
7606TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7607 FailingHttpTransactionFactory http_transaction_factory(
7608 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547609 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177610 context.set_http_transaction_factory(&http_transaction_factory);
7611 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547612 context.Init();
7613
7614 TestDelegate d;
davidben151423e2015-03-23 18:48:367615 scoped_ptr<URLRequest> req(
7616 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177617 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7618 // try to create an HttpNetworkTransaction synchronously on start).
7619 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197620 req->Start();
mmenke2281f3762015-11-02 20:38:177621 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547622 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177623 // Run pending error task, if there is one.
7624 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547625
7626 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177627 EXPECT_EQ(1, d.response_started_count());
7628 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
7629
7630 // NetworkDelegate should see the cancellation, but not the error.
7631 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7632 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547633}
7634
ttuttlec0c828492015-05-15 01:25:557635TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:557636 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557637
7638 TestDelegate d;
tommycli59a63432015-11-06 00:10:557639 GURL test_url(http_test_server()->GetURL("/"));
ttuttlec0c828492015-05-15 01:25:557640 scoped_ptr<URLRequest> req(
7641 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7642
7643 req->Start();
7644 base::RunLoop().Run();
7645
7646 EXPECT_TRUE(req->response_info().network_accessed);
7647}
7648
7649TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:557650 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557651
7652 // Populate the cache.
7653 TestDelegate d;
7654 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557655 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
ttuttlec0c828492015-05-15 01:25:557656 req->Start();
7657 base::RunLoop().Run();
7658
7659 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7660 EXPECT_TRUE(req->response_info().network_accessed);
7661 EXPECT_FALSE(req->response_info().was_cached);
7662
tommycli59a63432015-11-06 00:10:557663 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
ttuttlec0c828492015-05-15 01:25:557664 DEFAULT_PRIORITY, &d);
7665 req->Start();
7666 base::RunLoop().Run();
7667
7668 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7669 EXPECT_FALSE(req->response_info().network_accessed);
7670 EXPECT_TRUE(req->response_info().was_cached);
7671}
7672
7673TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:557674 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557675
7676 TestDelegate d;
tommycli59a63432015-11-06 00:10:557677 GURL test_url(http_test_server()->GetURL("/"));
ttuttlec0c828492015-05-15 01:25:557678 scoped_ptr<URLRequest> req(
7679 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7680 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7681
7682 req->Start();
7683 base::RunLoop().Run();
7684
7685 EXPECT_FALSE(req->response_info().network_accessed);
7686}
7687
bengr1bf8e942014-11-07 01:36:507688class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7689 public:
7690 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7691 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7692 // tests into the factory tests.
7693 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7694 }
7695
7696 void SetUpFactory() override {
7697 interceptor_ = new MockURLRequestInterceptor();
7698 job_factory_.reset(new URLRequestInterceptingJobFactory(
dchengc7eeda422015-12-26 03:56:487699 std::move(job_factory_), make_scoped_ptr(interceptor_)));
bengr1bf8e942014-11-07 01:36:507700 }
7701
7702 MockURLRequestInterceptor* interceptor() const {
7703 return interceptor_;
7704 }
7705
7706 private:
7707 MockURLRequestInterceptor* interceptor_;
7708};
7709
7710TEST_F(URLRequestInterceptorTestHTTP,
7711 NetworkDelegateNotificationOnRedirectIntercept) {
7712 interceptor()->set_intercept_redirect(true);
7713 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7714 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7715
tommycli59a63432015-11-06 00:10:557716 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507717
7718 TestDelegate d;
7719 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557720 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507721 req->Start();
7722 base::RunLoop().Run();
7723
7724 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7725 // Check we got one good response
7726 EXPECT_TRUE(req->status().is_success());
7727 if (req->status().is_success())
7728 EXPECT_EQ(200, req->response_headers()->response_code());
7729
7730 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7731 EXPECT_EQ(1, d.response_started_count());
7732 EXPECT_EQ(0, d.received_redirect_count());
7733
7734 EXPECT_EQ(1, default_network_delegate()->created_requests());
7735 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7736 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7737}
7738
7739TEST_F(URLRequestInterceptorTestHTTP,
7740 NetworkDelegateNotificationOnErrorIntercept) {
7741 // Intercept that error and respond with an OK response.
7742 interceptor()->set_intercept_final_response(true);
7743 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7744 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7745 default_network_delegate()->set_can_be_intercepted_on_error(true);
7746
tommycli59a63432015-11-06 00:10:557747 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507748
7749 TestDelegate d;
7750 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557751 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:367752 &d));
bengr1bf8e942014-11-07 01:36:507753 req->set_method("GET");
7754 req->Start();
7755 base::RunLoop().Run();
7756
7757 EXPECT_TRUE(interceptor()->did_intercept_final());
7758
7759 // Check we received one good response.
7760 EXPECT_TRUE(req->status().is_success());
7761 if (req->status().is_success())
7762 EXPECT_EQ(200, req->response_headers()->response_code());
7763 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7764 EXPECT_EQ(1, d.response_started_count());
7765 EXPECT_EQ(0, d.received_redirect_count());
7766
7767 EXPECT_EQ(1, default_network_delegate()->created_requests());
7768 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7769 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7770}
7771
7772TEST_F(URLRequestInterceptorTestHTTP,
7773 NetworkDelegateNotificationOnResponseIntercept) {
7774 // Intercept that error and respond with an OK response.
7775 interceptor()->set_intercept_final_response(true);
7776
7777 // Intercept with a real URLRequestHttpJob.
7778 interceptor()->set_use_url_request_http_job(true);
7779
tommycli59a63432015-11-06 00:10:557780 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507781
7782 TestDelegate d;
7783 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557784 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507785 req->set_method("GET");
7786 req->Start();
7787 base::RunLoop().Run();
7788
7789 EXPECT_TRUE(interceptor()->did_intercept_final());
7790
7791 // Check we received one good response.
7792 EXPECT_TRUE(req->status().is_success());
7793 if (req->status().is_success())
7794 EXPECT_EQ(200, req->response_headers()->response_code());
7795 EXPECT_EQ("hello", d.data_received());
7796 EXPECT_EQ(1, d.response_started_count());
7797 EXPECT_EQ(0, d.received_redirect_count());
7798
7799 EXPECT_EQ(1, default_network_delegate()->created_requests());
7800 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7801 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7802}
7803
mkwst0c5eab872014-11-21 14:18:547804class URLRequestTestReferrerPolicy : public URLRequestTest {
7805 public:
7806 URLRequestTestReferrerPolicy() {}
7807
tommycli59a63432015-11-06 00:10:557808 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
7809 origin_server_.reset(new EmbeddedTestServer(type));
7810 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
7811 origin_server_->AddDefaultHandlers(
7812 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7813 } else {
7814 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7815 }
mkwst0c5eab872014-11-21 14:18:547816 ASSERT_TRUE(origin_server_->Start());
7817 }
7818
tommycli59a63432015-11-06 00:10:557819 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
7820 net::EmbeddedTestServer::Type dest_type) {
7821 origin_server_.reset(new EmbeddedTestServer(origin_type));
7822 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7823 origin_server_->AddDefaultHandlers(
7824 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7825 } else {
7826 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7827 }
mkwst0c5eab872014-11-21 14:18:547828 ASSERT_TRUE(origin_server_->Start());
7829
tommycli59a63432015-11-06 00:10:557830 destination_server_.reset(new EmbeddedTestServer(dest_type));
7831 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7832 destination_server_->AddDefaultHandlers(
7833 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7834 } else {
7835 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7836 }
mkwst0c5eab872014-11-21 14:18:547837 ASSERT_TRUE(destination_server_->Start());
7838 }
7839
7840 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7841 const GURL& referrer,
7842 const GURL& expected) {
7843 // Create and execute the request: we'll only have a |destination_server_|
7844 // if the origins are meant to be distinct. Otherwise, we'll use the
7845 // |origin_server_| for both endpoints.
7846 GURL destination_url =
tommycli59a63432015-11-06 00:10:557847 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
7848 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:547849 GURL origin_url =
tommycli59a63432015-11-06 00:10:557850 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:547851
7852 TestDelegate d;
7853 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367854 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547855 req->set_referrer_policy(policy);
7856 req->SetReferrer(referrer.spec());
7857 req->Start();
7858 base::RunLoop().Run();
7859
7860 EXPECT_EQ(1, d.response_started_count());
7861 EXPECT_EQ(1, d.received_redirect_count());
7862 EXPECT_EQ(destination_url, req->url());
7863 EXPECT_TRUE(req->status().is_success());
7864 EXPECT_EQ(200, req->response_headers()->response_code());
7865
7866 EXPECT_EQ(expected.spec(), req->referrer());
7867 if (expected.is_empty())
7868 EXPECT_EQ("None", d.data_received());
7869 else
7870 EXPECT_EQ(expected.spec(), d.data_received());
7871 }
7872
tommycli59a63432015-11-06 00:10:557873 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:547874
7875 private:
tommycli59a63432015-11-06 00:10:557876 scoped_ptr<EmbeddedTestServer> origin_server_;
7877 scoped_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:547878};
7879
7880TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:557881 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547882
7883 VerifyReferrerAfterRedirect(
7884 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557885 origin_server()->GetURL("/path/to/file.html"),
7886 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547887
7888 VerifyReferrerAfterRedirect(
7889 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557890 origin_server()->GetURL("/path/to/file.html"),
7891 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547892
7893 VerifyReferrerAfterRedirect(
7894 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557895 origin_server()->GetURL("/path/to/file.html"),
7896 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547897
7898 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557899 origin_server()->GetURL("/path/to/file.html"),
7900 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547901}
7902
tommycli59a63432015-11-06 00:10:557903TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
7904 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
7905 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547906
7907 VerifyReferrerAfterRedirect(
7908 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557909 origin_server()->GetURL("/path/to/file.html"),
7910 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547911
7912 VerifyReferrerAfterRedirect(
7913 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557914 origin_server()->GetURL("/path/to/file.html"),
7915 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547916
7917 VerifyReferrerAfterRedirect(
7918 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557919 origin_server()->GetURL("/path/to/file.html"),
7920 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547921
7922 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557923 origin_server()->GetURL("/path/to/file.html"),
7924 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547925}
7926
7927TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:557928 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547929
7930 VerifyReferrerAfterRedirect(
7931 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557932 origin_server()->GetURL("/path/to/file.html"),
7933 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547934
7935 VerifyReferrerAfterRedirect(
7936 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557937 origin_server()->GetURL("/path/to/file.html"),
7938 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547939
7940 VerifyReferrerAfterRedirect(
7941 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557942 origin_server()->GetURL("/path/to/file.html"),
7943 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547944
7945 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557946 origin_server()->GetURL("/path/to/file.html"),
7947 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547948}
7949
tommycli59a63432015-11-06 00:10:557950TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7951 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
7952 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547953
7954 VerifyReferrerAfterRedirect(
7955 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557956 origin_server()->GetURL("/path/to/file.html"),
7957 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547958
7959 VerifyReferrerAfterRedirect(
7960 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557961 origin_server()->GetURL("/path/to/file.html"),
7962 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547963
7964 VerifyReferrerAfterRedirect(
7965 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557966 origin_server()->GetURL("/path/to/file.html"),
7967 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547968
7969 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557970 origin_server()->GetURL("/path/to/file.html"),
7971 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547972}
7973
tommycli59a63432015-11-06 00:10:557974TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7975 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
7976 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547977
7978 VerifyReferrerAfterRedirect(
7979 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557980 origin_server()->GetURL("/path/to/file.html"),
7981 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547982
7983 VerifyReferrerAfterRedirect(
7984 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557985 origin_server()->GetURL("/path/to/file.html"),
7986 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547987
7988 VerifyReferrerAfterRedirect(
7989 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557990 origin_server()->GetURL("/path/to/file.html"),
7991 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547992
7993 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557994 origin_server()->GetURL("/path/to/file.html"),
7995 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547996}
7997
tommycli59a63432015-11-06 00:10:557998TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7999 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8000 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548001
8002 VerifyReferrerAfterRedirect(
8003 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558004 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548005
8006 VerifyReferrerAfterRedirect(
8007 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558008 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548009
8010 VerifyReferrerAfterRedirect(
8011 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558012 origin_server()->GetURL("/path/to/file.html"),
8013 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548014
8015 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558016 origin_server()->GetURL("/path/to/file.html"),
8017 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548018}
8019
[email protected]73e0bba2009-02-19 22:57:098020class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:508021 public:
[email protected]ef2bf422012-05-11 03:27:098022 HTTPSRequestTest() : default_context_(true) {
8023 default_context_.set_network_delegate(&default_network_delegate_);
8024 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:508025 }
dcheng67be2b1f2014-10-27 21:47:298026 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:508027
8028 protected:
[email protected]ceefd7fd2012-11-29 00:36:248029 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:098030 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:468031};
8032
[email protected]c044616e2013-02-20 02:01:268033TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:558034 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8035 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228036 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118037 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:468038
[email protected]ea224582008-12-07 20:25:468039 TestDelegate d;
8040 {
[email protected]f7022f32014-08-21 16:32:198041 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558042 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198043 r->Start();
8044 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:468045
[email protected]255620da2013-08-19 13:14:298046 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:468047
8048 EXPECT_EQ(1, d.response_started_count());
8049 EXPECT_FALSE(d.received_data_before_response());
8050 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198051 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:198052 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198053 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198054 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198055 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:468056 }
[email protected]ea224582008-12-07 20:25:468057}
8058
[email protected]5774ada2010-07-15 06:30:548059TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:558060 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8061 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8062 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228063 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118064 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338065
8066 bool err_allowed = true;
8067 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8068 TestDelegate d;
8069 {
8070 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:198071 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558072 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338073
[email protected]f7022f32014-08-21 16:32:198074 r->Start();
8075 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338076
[email protected]255620da2013-08-19 13:14:298077 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338078
8079 EXPECT_EQ(1, d.response_started_count());
8080 EXPECT_FALSE(d.received_data_before_response());
8081 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178082 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338083 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198084 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178085 } else {
[email protected]bacff652009-03-31 17:50:338086 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178087 }
[email protected]bacff652009-03-31 17:50:338088 }
8089 }
8090}
8091
[email protected]5774ada2010-07-15 06:30:548092TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:558093 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8094 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
8095 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228096 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118097 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338098
8099 // Iterate from false to true, just so that we do the opposite of the
8100 // previous test in order to increase test coverage.
8101 bool err_allowed = false;
8102 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8103 TestDelegate d;
8104 {
8105 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:198106 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558107 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338108
[email protected]f7022f32014-08-21 16:32:198109 r->Start();
8110 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338111
[email protected]255620da2013-08-19 13:14:298112 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338113
8114 EXPECT_EQ(1, d.response_started_count());
8115 EXPECT_FALSE(d.received_data_before_response());
8116 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178117 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338118 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198119 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178120 } else {
[email protected]bacff652009-03-31 17:50:338121 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178122 }
[email protected]bacff652009-03-31 17:50:338123 }
8124 }
8125}
[email protected]73e0bba2009-02-19 22:57:098126
tommycli59a63432015-11-06 00:10:558127// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
8128// security state. (see http://crbug.com/550977).
8129#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:448130// This tests that a load of www.google.com with a certificate error sets
8131// the |certificate_errors_are_fatal| flag correctly. This flag will cause
8132// the interstitial to be fatal.
8133TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
tommycli59a63432015-11-06 00:10:558134 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8135 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8136 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448137 ASSERT_TRUE(test_server.Start());
8138
8139 // We require that the URL be www.google.com in order to pick up the
8140 // preloaded HSTS entries in the TransportSecurityState. This means that we
8141 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:248142 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448143
8144 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248145 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448146 TestURLRequestContext context(true);
8147 context.set_network_delegate(&network_delegate);
8148 context.set_host_resolver(&host_resolver);
8149 TransportSecurityState transport_security_state;
8150 context.set_transport_security_state(&transport_security_state);
8151 context.Init();
8152
8153 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198154 scoped_ptr<URLRequest> r(context.CreateRequest(
8155 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368156 test_server.host_port_pair().port())),
8157 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448158
[email protected]f7022f32014-08-21 16:32:198159 r->Start();
8160 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448161
[email protected]255620da2013-08-19 13:14:298162 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448163
8164 EXPECT_EQ(1, d.response_started_count());
8165 EXPECT_FALSE(d.received_data_before_response());
8166 EXPECT_TRUE(d.have_certificate_errors());
8167 EXPECT_TRUE(d.certificate_errors_are_fatal());
8168}
8169
8170// This tests that cached HTTPS page loads do not cause any updates to the
8171// TransportSecurityState.
8172TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
8173 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
8174 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:558175 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8176 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8177 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448178 ASSERT_TRUE(test_server.Start());
8179
[email protected]9e6968d2014-05-07 21:46:268180 // We require that the URL be www.google.com in order to pick up the static
8181 // and dynamic STS and PKP entries in the TransportSecurityState. This means
8182 // that we have to use a MockHostResolver in order to direct www.google.com to
8183 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448184
8185 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248186 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448187 TestURLRequestContext context(true);
8188 context.set_network_delegate(&network_delegate);
8189 context.set_host_resolver(&host_resolver);
8190 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:268191
martijnc0d6b622015-06-30 19:14:408192 TransportSecurityState::STSState static_sts_state;
8193 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268194 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408195 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:448196 context.set_transport_security_state(&transport_security_state);
8197 context.Init();
8198
martijnc0d6b622015-06-30 19:14:408199 TransportSecurityState::STSState dynamic_sts_state;
8200 TransportSecurityState::PKPState dynamic_pkp_state;
8201 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
8202 &dynamic_sts_state));
8203 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
8204 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268205
[email protected]316c1e5e2012-09-12 15:17:448206 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198207 scoped_ptr<URLRequest> r(context.CreateRequest(
8208 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368209 test_server.host_port_pair().port())),
8210 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448211
[email protected]f7022f32014-08-21 16:32:198212 r->Start();
8213 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448214
[email protected]255620da2013-08-19 13:14:298215 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448216
8217 EXPECT_EQ(1, d.response_started_count());
8218 EXPECT_FALSE(d.received_data_before_response());
8219 EXPECT_TRUE(d.have_certificate_errors());
8220 EXPECT_TRUE(d.certificate_errors_are_fatal());
8221
[email protected]9e6968d2014-05-07 21:46:268222 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408223 TransportSecurityState::STSState new_static_sts_state;
8224 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268225 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408226 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8227 TransportSecurityState::STSState new_dynamic_sts_state;
8228 TransportSecurityState::PKPState new_dynamic_pkp_state;
8229 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8230 "www.google.com", &new_dynamic_sts_state));
8231 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8232 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268233
martijnc0d6b622015-06-30 19:14:408234 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8235 EXPECT_EQ(new_static_sts_state.include_subdomains,
8236 static_sts_state.include_subdomains);
8237 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8238 static_pkp_state.include_subdomains);
8239 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.spki_hashes,
8240 static_pkp_state.spki_hashes));
8241 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.bad_spki_hashes,
8242 static_pkp_state.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:448243}
8244
[email protected]8ccc69f2012-11-28 19:52:148245// Make sure HSTS preserves a POST request's method and body.
8246TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8247 static const char kData[] = "hello world";
8248
tommycli59a63432015-11-06 00:10:558249 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8250 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228251 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148252 ASSERT_TRUE(test_server.Start());
8253
8254
8255 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8256 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:558257 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:228258 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148259 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148260
8261 // Force https for www.somewhere.com.
8262 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208263 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8264 bool include_subdomains = false;
8265 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8266 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148267
8268 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8269
8270 TestURLRequestContext context(true);
8271 context.set_host_resolver(&host_resolver);
8272 context.set_transport_security_state(&transport_security_state);
8273 context.set_network_delegate(&network_delegate);
8274 context.Init();
8275
8276 TestDelegate d;
8277 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8278 // cause a certificate error. Ignore the error.
8279 d.set_allow_certificate_errors(true);
8280
[email protected]f7022f32014-08-21 16:32:198281 scoped_ptr<URLRequest> req(context.CreateRequest(
8282 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368283 test_server.host_port_pair().port())),
8284 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198285 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078286 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148287
[email protected]f7022f32014-08-21 16:32:198288 req->Start();
[email protected]255620da2013-08-19 13:14:298289 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148290
[email protected]f7022f32014-08-21 16:32:198291 EXPECT_EQ("https", req->url().scheme());
8292 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148293 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408294
8295 LoadTimingInfo load_timing_info;
8296 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8297 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8298 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148299}
8300
rob4e0be1f2014-09-11 23:40:228301// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8302TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8303 static const char kOriginHeaderValue[] = "http://www.example.com";
8304
tommycli59a63432015-11-06 00:10:558305 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8306 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:228307 ASSERT_TRUE(test_server.Start());
8308
8309 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8310 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:558311 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
8312 // default.
rob4e0be1f2014-09-11 23:40:228313 MockHostResolver host_resolver;
8314
8315 TransportSecurityState transport_security_state;
8316 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8317 bool include_subdomains = false;
8318 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8319
8320 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8321
8322 MockCertVerifier cert_verifier;
8323 cert_verifier.set_default_result(OK);
8324
8325 TestURLRequestContext context(true);
8326 context.set_host_resolver(&host_resolver);
8327 context.set_transport_security_state(&transport_security_state);
8328 context.set_network_delegate(&network_delegate);
8329 context.set_cert_verifier(&cert_verifier);
8330 context.Init();
8331
8332 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8333 test_server.host_port_pair().port()));
8334 url::Replacements<char> replacements;
8335 const char kNewScheme[] = "https";
8336 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8337 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8338
8339 TestDelegate d;
8340 // Quit on redirect to allow response header inspection upon redirect.
8341 d.set_quit_on_redirect(true);
8342
davidben151423e2015-03-23 18:48:368343 scoped_ptr<URLRequest> req(
8344 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228345 // Set Origin header to simulate a cross-origin request.
8346 HttpRequestHeaders request_headers;
8347 request_headers.SetHeader("Origin", kOriginHeaderValue);
8348 req->SetExtraRequestHeaders(request_headers);
8349
8350 req->Start();
8351 base::RunLoop().Run();
8352
8353 EXPECT_EQ(1, d.received_redirect_count());
8354
8355 const HttpResponseHeaders* headers = req->response_headers();
8356 std::string redirect_location;
8357 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8358 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8359
8360 std::string received_cors_header;
8361 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8362 &received_cors_header));
8363 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8364}
8365
Adam Ricecb76ac62015-02-20 05:33:258366// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
8367// are performed in net/websockets/websocket_end_to_end_test.cc.
8368TEST(WebSocketURLRequestTest, HSTSApplied) {
8369 TestNetworkDelegate network_delegate;
8370 TransportSecurityState transport_security_state;
8371 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8372 bool include_subdomains = false;
8373 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8374 TestURLRequestContext context(true);
8375 context.set_transport_security_state(&transport_security_state);
8376 context.set_network_delegate(&network_delegate);
8377 context.Init();
8378 GURL ws_url("ws://example.net/echo");
8379 TestDelegate delegate;
8380 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:368381 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:258382 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
8383 EXPECT_TRUE(ws_url.SchemeIs("wss"));
8384}
8385
[email protected]316c1e5e2012-09-12 15:17:448386namespace {
8387
8388class SSLClientAuthTestDelegate : public TestDelegate {
8389 public:
8390 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8391 }
dchengb03027d2014-10-21 12:00:208392 void OnCertificateRequested(URLRequest* request,
8393 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448394 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178395 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448396 }
8397 int on_certificate_requested_count() {
8398 return on_certificate_requested_count_;
8399 }
8400 private:
8401 int on_certificate_requested_count_;
8402};
8403
8404} // namespace
8405
8406// TODO(davidben): Test the rest of the code. Specifically,
8407// - Filtering which certificates to select.
8408// - Sending a certificate back.
8409// - Getting a certificate request in an SSL renegotiation sending the
8410// HTTP request.
8411TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:558412 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8413 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:128414 ssl_config.client_cert_type =
8415 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
tommycli59a63432015-11-06 00:10:558416 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
8417 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228418 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448419 ASSERT_TRUE(test_server.Start());
8420
8421 SSLClientAuthTestDelegate d;
8422 {
[email protected]f7022f32014-08-21 16:32:198423 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558424 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448425
[email protected]f7022f32014-08-21 16:32:198426 r->Start();
8427 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448428
[email protected]255620da2013-08-19 13:14:298429 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448430
8431 EXPECT_EQ(1, d.on_certificate_requested_count());
8432 EXPECT_FALSE(d.received_data_before_response());
8433 EXPECT_EQ(0, d.bytes_received());
8434
8435 // Send no certificate.
8436 // TODO(davidben): Get temporary client cert import (with keys) working on
8437 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:548438 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:448439
[email protected]255620da2013-08-19 13:14:298440 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448441
8442 EXPECT_EQ(1, d.response_started_count());
8443 EXPECT_FALSE(d.received_data_before_response());
8444 EXPECT_NE(0, d.bytes_received());
8445 }
8446}
8447
8448TEST_F(HTTPSRequestTest, ResumeTest) {
8449 // Test that we attempt a session resume when making two connections to the
8450 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228451 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448452 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228453 SpawnedTestServer test_server(
8454 SpawnedTestServer::TYPE_HTTPS,
8455 ssl_options,
8456 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448457 ASSERT_TRUE(test_server.Start());
8458
8459 SSLClientSocket::ClearSessionCache();
8460
8461 {
8462 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198463 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368464 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448465
[email protected]f7022f32014-08-21 16:32:198466 r->Start();
8467 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448468
[email protected]255620da2013-08-19 13:14:298469 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448470
8471 EXPECT_EQ(1, d.response_started_count());
8472 }
8473
8474 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8475 CloseAllConnections();
8476
8477 {
8478 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198479 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368480 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448481
[email protected]f7022f32014-08-21 16:32:198482 r->Start();
8483 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448484
[email protected]255620da2013-08-19 13:14:298485 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448486
8487 // The response will look like;
8488 // insert abc
8489 // lookup abc
8490 // insert xyz
8491 //
8492 // With a newline at the end which makes the split think that there are
8493 // four lines.
8494
8495 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298496 std::vector<std::string> lines = base::SplitString(
8497 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448498 ASSERT_EQ(4u, lines.size()) << d.data_received();
8499
8500 std::string session_id;
8501
8502 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298503 std::vector<std::string> parts = base::SplitString(
8504 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448505 ASSERT_EQ(2u, parts.size());
8506 if (i == 0) {
8507 EXPECT_EQ("insert", parts[0]);
8508 session_id = parts[1];
8509 } else {
8510 EXPECT_EQ("lookup", parts[0]);
8511 EXPECT_EQ(session_id, parts[1]);
8512 }
8513 }
8514 }
8515}
8516
Adam Langley32352ad2014-10-14 22:31:008517// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8518// the result of fetching "ssl-session-cache" from the test server, indicates
8519// that exactly two different sessions were inserted, with no lookups etc.
8520static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298521 std::vector<std::string> lines = base::SplitString(
8522 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008523 ASSERT_EQ(3u, lines.size()) << session_info;
8524
8525 std::string session_id;
8526 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298527 std::vector<std::string> parts = base::SplitString(
8528 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008529 ASSERT_EQ(2u, parts.size());
8530 EXPECT_EQ("insert", parts[0]);
8531 if (i == 0) {
8532 session_id = parts[1];
8533 } else {
8534 EXPECT_NE(session_id, parts[1]);
8535 }
8536 }
8537}
8538
[email protected]316c1e5e2012-09-12 15:17:448539TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8540 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8541 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228542 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448543 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228544 SpawnedTestServer test_server(
8545 SpawnedTestServer::TYPE_HTTPS,
8546 ssl_options,
8547 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448548 ASSERT_TRUE(test_server.Start());
8549
8550 SSLClientSocket::ClearSessionCache();
8551
8552 {
8553 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198554 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368555 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448556
[email protected]f7022f32014-08-21 16:32:198557 r->Start();
8558 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448559
[email protected]255620da2013-08-19 13:14:298560 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448561
8562 EXPECT_EQ(1, d.response_started_count());
8563 }
8564
8565 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8566 HttpNetworkSession::Params params;
8567 params.host_resolver = default_context_.host_resolver();
8568 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118569 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:448570 params.proxy_service = default_context_.proxy_service();
8571 params.ssl_config_service = default_context_.ssl_config_service();
8572 params.http_auth_handler_factory =
8573 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:418574 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:448575 params.http_server_properties = default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:448576
mmenkee65e7af2015-10-13 17:16:428577 HttpNetworkSession network_session(params);
[email protected]cba24642014-08-15 20:49:598578 scoped_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428579 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448580
8581 default_context_.set_http_transaction_factory(cache.get());
8582
8583 {
8584 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198585 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368586 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448587
[email protected]f7022f32014-08-21 16:32:198588 r->Start();
8589 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448590
[email protected]255620da2013-08-19 13:14:298591 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448592
8593 // The response will look like;
8594 // insert abc
8595 // insert xyz
8596 //
8597 // With a newline at the end which makes the split think that there are
8598 // three lines.
8599
8600 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008601 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448602 }
8603}
8604
davidben8ecc3072014-09-03 23:19:098605#if defined(OS_WIN)
8606
8607namespace {
8608
8609bool IsECDSACipherSuite(uint16_t cipher_suite) {
8610 const char* key_exchange;
8611 const char* cipher;
8612 const char* mac;
8613 bool is_aead;
8614 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
8615 return std::string(key_exchange).find("ECDSA") != std::string::npos;
8616}
8617
8618} // namespace
8619
8620// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
8621// verified.
davidben9399c952014-10-07 04:09:118622TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:098623 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
8624 LOG(INFO) << "Skipping test on this version.";
8625 return;
8626 }
8627
tommycli59a63432015-11-06 00:10:558628 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8629 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
davidben8ecc3072014-09-03 23:19:098630 ASSERT_TRUE(test_server.Start());
8631
8632 TestDelegate d;
8633 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558634 test_server.GetURL("/client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:098635 r->Start();
8636 EXPECT_TRUE(r->is_pending());
8637
8638 base::RunLoop().Run();
8639
8640 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298641 std::vector<std::string> lines = base::SplitString(
8642 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
davidben8ecc3072014-09-03 23:19:098643
8644 for (size_t i = 0; i < lines.size(); i++) {
8645 int cipher_suite;
8646 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
8647 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
8648 << "ClientHello advertised " << cipher_suite;
8649 }
8650}
8651
8652#endif // OS_WIN
8653
Adam Langley32352ad2014-10-14 22:31:008654class FallbackTestURLRequestContext : public TestURLRequestContext {
8655 public:
8656 explicit FallbackTestURLRequestContext(bool delay_initialization)
8657 : TestURLRequestContext(delay_initialization) {}
8658
avibf0746c2015-12-09 19:53:148659 void set_fallback_min_version(uint16_t version) {
nharperb7441ef2016-01-25 23:54:148660 TestSSLConfigService* ssl_config_service = new TestSSLConfigService(
8661 true /* check for EV */, false /* online revocation checking */,
8662 false /* require rev. checking for local
8663 anchors */,
8664 false /* token binding enabled */);
Adam Langley32352ad2014-10-14 22:31:008665 ssl_config_service->set_fallback_min_version(version);
8666 set_ssl_config_service(ssl_config_service);
8667 }
8668};
8669
[email protected]48d2b7c52014-06-27 01:16:558670class HTTPSFallbackTest : public testing::Test {
8671 public:
Adam Langley32352ad2014-10-14 22:31:008672 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298673 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558674
8675 protected:
8676 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8677 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008678 context_.Init();
8679 delegate_.set_allow_certificate_errors(true);
8680
[email protected]48d2b7c52014-06-27 01:16:558681 SpawnedTestServer test_server(
8682 SpawnedTestServer::TYPE_HTTPS,
8683 ssl_options,
8684 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8685 ASSERT_TRUE(test_server.Start());
8686
tommycli59a63432015-11-06 00:10:558687 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
8688 &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558689 request_->Start();
8690
8691 base::RunLoop().Run();
8692 }
8693
avibf0746c2015-12-09 19:53:148694 void set_fallback_min_version(uint16_t version) {
Adam Langley32352ad2014-10-14 22:31:008695 context_.set_fallback_min_version(version);
8696 }
8697
[email protected]48d2b7c52014-06-27 01:16:558698 void ExpectConnection(int version) {
8699 EXPECT_EQ(1, delegate_.response_started_count());
8700 EXPECT_NE(0, delegate_.bytes_received());
8701 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8702 request_->ssl_info().connection_status));
8703 EXPECT_TRUE(request_->ssl_info().connection_status &
8704 SSL_CONNECTION_VERSION_FALLBACK);
8705 }
8706
8707 void ExpectFailure(int error) {
8708 EXPECT_EQ(1, delegate_.response_started_count());
8709 EXPECT_FALSE(request_->status().is_success());
8710 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8711 EXPECT_EQ(error, request_->status().error());
8712 }
8713
8714 private:
8715 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008716 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558717 scoped_ptr<URLRequest> request_;
8718};
8719
davidbenb127ca82015-06-15 19:05:428720// Tests the TLS 1.0 fallback doesn't happen.
8721TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558722 SpawnedTestServer::SSLOptions ssl_options(
8723 SpawnedTestServer::SSLOptions::CERT_OK);
8724 ssl_options.tls_intolerant =
8725 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8726
8727 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:558728 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:428729}
8730
davidben3b267512016-02-24 19:46:558731// Tests the TLS 1.1 fallback doesn't happen but 1.2-intolerance is detected.
8732TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:428733 SpawnedTestServer::SSLOptions ssl_options(
8734 SpawnedTestServer::SSLOptions::CERT_OK);
8735 ssl_options.tls_intolerant =
8736 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8737
8738 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:558739 ExpectFailure(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION);
8740}
8741
8742// Tests the TLS 1.1 fallback when explicitly enabled.
8743TEST_F(HTTPSFallbackTest, TLSv1_1Fallback) {
8744 SpawnedTestServer::SSLOptions ssl_options(
8745 SpawnedTestServer::SSLOptions::CERT_OK);
8746 ssl_options.tls_intolerant =
8747 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8748
8749 set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
8750 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428751 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
8752}
8753
davidben3b267512016-02-24 19:46:558754// Tests that the TLS 1.1 fallback, if enabled, triggers on closed connections.
davidbenb127ca82015-06-15 19:05:428755TEST_F(HTTPSFallbackTest, TLSv1_1FallbackClosed) {
davidbenb127ca82015-06-15 19:05:428756 SpawnedTestServer::SSLOptions ssl_options(
8757 SpawnedTestServer::SSLOptions::CERT_OK);
8758 ssl_options.tls_intolerant =
8759 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8760 ssl_options.tls_intolerance_type =
8761 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8762
davidben3b267512016-02-24 19:46:558763 set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
davidbenb127ca82015-06-15 19:05:428764 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8765 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558766}
8767
8768// This test is disabled on Android because the remote test server doesn't cause
8769// a TCP reset.
8770#if !defined(OS_ANDROID)
davidben3b267512016-02-24 19:46:558771// Tests fallback to TLS 1.1, if enabled, on connection reset.
davidbenb127ca82015-06-15 19:05:428772TEST_F(HTTPSFallbackTest, TLSv1_1FallbackReset) {
[email protected]48d2b7c52014-06-27 01:16:558773 SpawnedTestServer::SSLOptions ssl_options(
8774 SpawnedTestServer::SSLOptions::CERT_OK);
8775 ssl_options.tls_intolerant =
davidbenb127ca82015-06-15 19:05:428776 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
[email protected]48d2b7c52014-06-27 01:16:558777 ssl_options.tls_intolerance_type =
8778 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8779
davidben3b267512016-02-24 19:46:558780 set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558781 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428782 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558783}
8784#endif // !OS_ANDROID
8785
davidben3b267512016-02-24 19:46:558786// Tests that we don't fallback, even if enabled, on handshake failure with
8787// servers that implement TLS_FALLBACK_SCSV. Also ensure that the original error
8788// code is reported.
[email protected]48d2b7c52014-06-27 01:16:558789TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558790 SpawnedTestServer::SSLOptions ssl_options(
8791 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438792 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558793 // a version fallback.
8794 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438795 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558796 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8797 // connections are rejected.
8798 ssl_options.fallback_scsv_enabled = true;
8799
davidben3b267512016-02-24 19:46:558800 set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558801 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8802
8803 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8804 // intolerance. If the fallback SCSV is processed when the original error
8805 // that caused the fallback should be returned, which should be
8806 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8807 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8808}
8809
davidben3b267512016-02-24 19:46:558810// Tests that we don't fallback, even if enabled, on connection closed with
8811// servers that implement TLS_FALLBACK_SCSV. Also ensure that the original error
8812// code is reported.
[email protected]12833302014-07-02 01:57:318813TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318814 SpawnedTestServer::SSLOptions ssl_options(
8815 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438816 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318817 // a version fallback.
8818 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438819 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318820 ssl_options.tls_intolerance_type =
8821 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8822 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8823 // connections are rejected.
8824 ssl_options.fallback_scsv_enabled = true;
8825
davidben3b267512016-02-24 19:46:558826 set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
[email protected]12833302014-07-02 01:57:318827 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8828
8829 // The original error should be replayed on rejected fallback.
8830 ExpectFailure(ERR_CONNECTION_CLOSED);
8831}
8832
davidbenb937d6c2015-05-14 04:53:428833// Test that fallback probe connections don't cause sessions to be cached.
8834TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008835 SpawnedTestServer::SSLOptions ssl_options(
8836 SpawnedTestServer::SSLOptions::CERT_OK);
8837 ssl_options.tls_intolerant =
davidben3b267512016-02-24 19:46:558838 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
Adam Langley32352ad2014-10-14 22:31:008839 ssl_options.tls_intolerance_type =
8840 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8841 ssl_options.record_resume = true;
8842
8843 SpawnedTestServer test_server(
8844 SpawnedTestServer::TYPE_HTTPS,
8845 ssl_options,
8846 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8847 ASSERT_TRUE(test_server.Start());
8848
8849 SSLClientSocket::ClearSessionCache();
8850
davidben3b267512016-02-24 19:46:558851 // Make a connection that does a probe fallback to TLSv1.1 but fails because
8852 // fallback is disabled. We don't wish a session for this connection to be
8853 // inserted locally.
Adam Langley32352ad2014-10-14 22:31:008854 {
8855 TestDelegate delegate;
8856 FallbackTestURLRequestContext context(true);
8857
8858 context.Init();
8859 scoped_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558860 test_server.GetURL("/"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008861 request->Start();
8862
8863 base::RunLoop().Run();
8864
8865 EXPECT_EQ(1, delegate.response_started_count());
8866 EXPECT_FALSE(request->status().is_success());
8867 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8868 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8869 request->status().error());
8870 }
8871
davidben3b267512016-02-24 19:46:558872 // Now allow TLSv1.1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008873 {
8874 TestDelegate delegate;
8875 FallbackTestURLRequestContext context(true);
davidben3b267512016-02-24 19:46:558876 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
Adam Langley32352ad2014-10-14 22:31:008877
8878 context.Init();
davidben151423e2015-03-23 18:48:368879 scoped_ptr<URLRequest> request(context.CreateRequest(
8880 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008881 request->Start();
8882
8883 base::RunLoop().Run();
8884
8885 EXPECT_EQ(1, delegate.response_started_count());
8886 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428887 EXPECT_EQ(
davidben3b267512016-02-24 19:46:558888 SSL_CONNECTION_VERSION_TLS1_1,
davidbenb937d6c2015-05-14 04:53:428889 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008890 EXPECT_TRUE(request->ssl_info().connection_status &
8891 SSL_CONNECTION_VERSION_FALLBACK);
8892
8893 std::vector<std::string> lines;
8894 // If no sessions were cached then the server should have seen two sessions
8895 // inserted with no lookups.
8896 AssertTwoDistinctSessionsInserted(delegate.data_received());
8897 }
8898}
8899
[email protected]a8fed1742013-12-27 02:14:248900class HTTPSSessionTest : public testing::Test {
8901 public:
8902 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598903 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248904
8905 default_context_.set_network_delegate(&default_network_delegate_);
8906 default_context_.set_cert_verifier(&cert_verifier_);
8907 default_context_.Init();
8908 }
dcheng67be2b1f2014-10-27 21:47:298909 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248910
8911 protected:
8912 MockCertVerifier cert_verifier_;
8913 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8914 TestURLRequestContext default_context_;
8915};
8916
8917// Tests that session resumption is not attempted if an invalid certificate
8918// is presented.
8919TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8920 SpawnedTestServer::SSLOptions ssl_options;
8921 ssl_options.record_resume = true;
8922 SpawnedTestServer test_server(
8923 SpawnedTestServer::TYPE_HTTPS,
8924 ssl_options,
8925 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8926 ASSERT_TRUE(test_server.Start());
8927
8928 SSLClientSocket::ClearSessionCache();
8929
8930 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598931 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248932 {
8933 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198934 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368935 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248936
[email protected]f7022f32014-08-21 16:32:198937 r->Start();
8938 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248939
8940 base::RunLoop().Run();
8941
8942 EXPECT_EQ(1, d.response_started_count());
8943 }
8944
8945 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8946 CloseAllConnections();
8947
8948 // Now change the certificate to be acceptable (so that the response is
8949 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598950 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248951 {
8952 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198953 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368954 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248955
[email protected]f7022f32014-08-21 16:32:198956 r->Start();
8957 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248958
8959 base::RunLoop().Run();
8960
8961 // The response will look like;
8962 // insert abc
8963 // insert xyz
8964 //
8965 // With a newline at the end which makes the split think that there are
8966 // three lines.
8967 //
8968 // If a session was presented (eg: a bug), then the response would look
8969 // like;
8970 // insert abc
8971 // lookup abc
8972 // insert xyz
8973
8974 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008975 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248976 }
8977}
8978
[email protected]dffe8242012-03-20 15:14:278979// This the fingerprint of the "Testing CA" certificate used by the testserver.
8980// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268981static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278982 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8983 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8984
[email protected]51523f52013-07-31 21:57:288985// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8986// testserver.
8987static const SHA256HashValue kOCSPTestCertSPKI = { {
8988 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8989 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8990 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8991 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8992} };
8993
[email protected]dffe8242012-03-20 15:14:278994// This is the policy OID contained in the certificates that testserver
8995// generates.
8996static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8997
8998class HTTPSOCSPTest : public HTTPSRequestTest {
8999 public:
9000 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:099001 : context_(true),
[email protected]b6f2de32012-08-17 04:35:089002 ev_test_policy_(
9003 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
9004 kOCSPTestCertFingerprint,
9005 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:029006 }
9007
dcheng67be2b1f2014-10-27 21:47:299008 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:099009 SetupContext(&context_);
9010 context_.Init();
[email protected]dffe8242012-03-20 15:14:279011
[email protected]cba24642014-08-15 20:49:599012 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:209013 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:429014 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:509015 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:279016
davidben71f35ff2015-04-17 20:54:489017#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:099018 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:279019 EnsureNSSHttpIOInit();
9020#endif
9021 }
9022
[email protected]ce7d0cbc2013-05-03 18:57:229023 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:279024 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:539025 // We always overwrite out_cert_status.
9026 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:229027 SpawnedTestServer test_server(
9028 SpawnedTestServer::TYPE_HTTPS,
9029 ssl_options,
9030 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:279031 ASSERT_TRUE(test_server.Start());
9032
9033 TestDelegate d;
9034 d.set_allow_certificate_errors(true);
tommycli59a63432015-11-06 00:10:559035 scoped_ptr<URLRequest> r(
9036 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199037 r->Start();
[email protected]dffe8242012-03-20 15:14:279038
[email protected]255620da2013-08-19 13:14:299039 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:279040
9041 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:199042 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:279043 }
9044
dcheng67be2b1f2014-10-27 21:47:299045 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:489046#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279047 ShutdownNSSHttpIO();
9048#endif
9049 }
9050
[email protected]a13234c2012-03-20 21:45:029051 protected:
9052 // SetupContext configures the URLRequestContext that will be used for making
9053 // connetions to testserver. This can be overridden in test subclasses for
9054 // different behaviour.
9055 virtual void SetupContext(URLRequestContext* context) {
nharperb7441ef2016-01-25 23:54:149056 context->set_ssl_config_service(new TestSSLConfigService(
9057 true /* check for EV */, true /* online revocation checking */,
9058 false /* require rev. checking for local
9059 anchors */,
9060 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029061 }
9062
[email protected]dffe8242012-03-20 15:14:279063 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:099064 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:089065 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:279066};
9067
[email protected]a13234c2012-03-20 21:45:029068static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:019069#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:029070 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
9071 // have that ability on other platforms.
9072 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
9073#else
9074 return 0;
9075#endif
9076}
9077
[email protected]3a86a712013-07-30 07:16:209078// SystemSupportsHardFailRevocationChecking returns true iff the current
9079// operating system supports revocation checking and can distinguish between
9080// situations where a given certificate lacks any revocation information (eg:
9081// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
9082// revocation information cannot be obtained (eg: the CRL was unreachable).
9083// If it does not, then tests which rely on 'hard fail' behaviour should be
9084// skipped.
9085static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:489086#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:209087 return true;
9088#else
9089 return false;
9090#endif
9091}
9092
[email protected]a13234c2012-03-20 21:45:029093// SystemUsesChromiumEVMetadata returns true iff the current operating system
9094// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
9095// several tests are effected because our testing EV certificate won't be
9096// recognised as EV.
9097static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:329098#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:579099 // http://crbug.com/117478 - OpenSSL does not support EV validation.
9100 return false;
[email protected]e1b2d732014-03-28 16:20:329101#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
9102 // On OS X and Android, we use the system to tell us whether a certificate is
9103 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:019104 return false;
9105#else
9106 return true;
9107#endif
9108}
9109
[email protected]b6f2de32012-08-17 04:35:089110static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:009111#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:579112 // http://crbug.com/117478 - OpenSSL does not support OCSP.
9113 return false;
9114#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:029115 return base::win::GetVersion() >= base::win::VERSION_VISTA;
9116#elif defined(OS_ANDROID)
9117 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
9118 return false;
9119#else
9120 return true;
9121#endif
9122}
9123
davidbend1fb2f12014-11-08 02:51:009124static bool SystemSupportsOCSPStapling() {
mathpc992e602015-10-21 20:34:039125#if defined(USE_NSS_CERTS) || defined(OS_IOS)
9126 return true;
9127#elif defined(OS_WIN)
9128 return base::win::GetVersion() >= base::win::VERSION_VISTA;
9129#else
9130 return false;
9131#endif
davidbend1fb2f12014-11-08 02:51:009132}
9133
[email protected]dffe8242012-03-20 15:14:279134TEST_F(HTTPSOCSPTest, Valid) {
9135 if (!SystemSupportsOCSP()) {
9136 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9137 return;
9138 }
9139
[email protected]ce7d0cbc2013-05-03 18:57:229140 SpawnedTestServer::SSLOptions ssl_options(
9141 SpawnedTestServer::SSLOptions::CERT_AUTO);
9142 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:279143
[email protected]924e9f92012-12-16 22:00:539144 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129145 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279146
9147 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9148
[email protected]a13234c2012-03-20 21:45:029149 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9150 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:279151
9152 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9153}
9154
9155TEST_F(HTTPSOCSPTest, Revoked) {
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_REVOKED;
[email protected]dffe8242012-03-20 15:14:279164
9165 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129166 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279167
[email protected]a592c0432012-12-01 18:10:299168#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:279169 // Doesn't pass on OS X yet for reasons that need to be investigated.
9170 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9171#endif
9172 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9173 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9174}
9175
9176TEST_F(HTTPSOCSPTest, Invalid) {
9177 if (!SystemSupportsOCSP()) {
9178 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9179 return;
9180 }
9181
[email protected]ce7d0cbc2013-05-03 18:57:229182 SpawnedTestServer::SSLOptions ssl_options(
9183 SpawnedTestServer::SSLOptions::CERT_AUTO);
9184 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:279185
[email protected]924e9f92012-12-16 22:00:539186 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129187 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279188
[email protected]a13234c2012-03-20 21:45:029189 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:279190 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279191
9192 // Without a positive OCSP response, we shouldn't show the EV status.
9193 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9194 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9195}
[email protected]a13234c2012-03-20 21:45:029196
davidbend1fb2f12014-11-08 02:51:009197TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:039198 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009199 LOG(WARNING)
9200 << "Skipping test because system doesn't support OCSP stapling";
9201 return;
9202 }
9203
9204 SpawnedTestServer::SSLOptions ssl_options(
9205 SpawnedTestServer::SSLOptions::CERT_AUTO);
9206 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9207 ssl_options.staple_ocsp_response = true;
9208 ssl_options.ocsp_server_unavailable = true;
9209
9210 CertStatus cert_status;
9211 DoConnection(ssl_options, &cert_status);
9212
9213 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9214
9215 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9216 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9217
9218 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9219}
9220
davidben6c3191b2014-11-21 22:38:049221// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489222#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049223#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9224#else
9225#define MAYBE_RevokedStapled RevokedStapled
9226#endif
9227TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:039228 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009229 LOG(WARNING)
9230 << "Skipping test because system doesn't support OCSP stapling";
9231 return;
9232 }
9233
9234 SpawnedTestServer::SSLOptions ssl_options(
9235 SpawnedTestServer::SSLOptions::CERT_AUTO);
9236 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9237 ssl_options.staple_ocsp_response = true;
9238 ssl_options.ocsp_server_unavailable = true;
9239
9240 CertStatus cert_status;
9241 DoConnection(ssl_options, &cert_status);
9242
9243 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9244 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9245 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9246}
9247
[email protected]3a86a712013-07-30 07:16:209248class HTTPSHardFailTest : public HTTPSOCSPTest {
9249 protected:
dchengb03027d2014-10-21 12:00:209250 void SetupContext(URLRequestContext* context) override {
nharperb7441ef2016-01-25 23:54:149251 context->set_ssl_config_service(new TestSSLConfigService(
9252 false /* check for EV */, false /* online revocation checking */,
9253 true /* require rev. checking for local
9254 anchors */,
9255 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:209256 }
9257};
9258
[email protected]3a86a712013-07-30 07:16:209259TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
9260 if (!SystemSupportsOCSP()) {
9261 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9262 return;
9263 }
9264
9265 if (!SystemSupportsHardFailRevocationChecking()) {
9266 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
9267 << "revocation checking";
9268 return;
9269 }
9270
9271 SpawnedTestServer::SSLOptions ssl_options(
9272 SpawnedTestServer::SSLOptions::CERT_AUTO);
9273 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9274
9275 CertStatus cert_status;
9276 DoConnection(ssl_options, &cert_status);
9277
9278 EXPECT_EQ(CERT_STATUS_REVOKED,
9279 cert_status & CERT_STATUS_REVOKED);
9280
9281 // Without a positive OCSP response, we shouldn't show the EV status.
9282 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9283}
9284
[email protected]a13234c2012-03-20 21:45:029285class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
9286 protected:
dchengb03027d2014-10-21 12:00:209287 void SetupContext(URLRequestContext* context) override {
nharperb7441ef2016-01-25 23:54:149288 context->set_ssl_config_service(new TestSSLConfigService(
9289 true /* check for EV */, false /* online revocation checking */,
9290 false /* require rev. checking for local
9291 anchors */,
9292 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029293 }
9294};
9295
9296TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
9297 if (!SystemSupportsOCSP()) {
9298 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9299 return;
9300 }
9301
[email protected]ce7d0cbc2013-05-03 18:57:229302 SpawnedTestServer::SSLOptions ssl_options(
9303 SpawnedTestServer::SSLOptions::CERT_AUTO);
9304 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029305 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9306
[email protected]924e9f92012-12-16 22:00:539307 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129308 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029309
9310 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9311 cert_status & CERT_STATUS_ALL_ERRORS);
9312
9313 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089314 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9315 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029316}
9317
[email protected]be0fff62013-08-29 23:37:489318TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
9319 if (!SystemSupportsOCSP()) {
9320 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9321 return;
9322 }
9323
9324 SpawnedTestServer::SSLOptions ssl_options(
9325 SpawnedTestServer::SSLOptions::CERT_AUTO);
9326 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9327 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9328
9329 CertStatus cert_status;
9330 DoConnection(ssl_options, &cert_status);
9331
9332 // Currently only works for Windows. When using NSS or OS X, it's not
9333 // possible to determine whether the check failed because of actual
9334 // revocation or because there was an OCSP failure.
9335#if defined(OS_WIN)
9336 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9337#else
9338 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9339#endif
9340
9341 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9342 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9343 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9344}
9345
[email protected]a13234c2012-03-20 21:45:029346TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
9347 if (!SystemSupportsOCSP()) {
9348 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9349 return;
9350 }
9351
[email protected]ce7d0cbc2013-05-03 18:57:229352 SpawnedTestServer::SSLOptions ssl_options(
9353 SpawnedTestServer::SSLOptions::CERT_AUTO);
9354 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:029355 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9356
9357 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129358 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029359
9360 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9361
9362 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9363 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:089364 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9365 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029366}
9367
9368TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
9369 if (!SystemSupportsOCSP()) {
9370 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9371 return;
9372 }
9373
[email protected]ce7d0cbc2013-05-03 18:57:229374 SpawnedTestServer::SSLOptions ssl_options(
9375 SpawnedTestServer::SSLOptions::CERT_AUTO);
9376 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029377 SSLConfigService::SetCRLSet(
9378 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9379
9380 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129381 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029382
9383 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9384 cert_status & CERT_STATUS_ALL_ERRORS);
9385
9386 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089387 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9388 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029389}
9390
[email protected]51523f52013-07-31 21:57:289391TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9392 if (!SystemSupportsOCSP()) {
9393 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9394 return;
9395 }
9396
9397 SpawnedTestServer::SSLOptions ssl_options(
9398 SpawnedTestServer::SSLOptions::CERT_AUTO);
9399 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9400 SSLConfigService::SetCRLSet(
9401 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9402 false, &kOCSPTestCertSPKI, "")));
9403
9404 CertStatus cert_status;
9405 DoConnection(ssl_options, &cert_status);
9406
9407 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9408 // revocation check for EV.
9409 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9410 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9411 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9412 EXPECT_FALSE(
9413 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9414}
9415
9416TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9417 if (!SystemSupportsOCSP()) {
9418 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9419 return;
9420 }
9421
[email protected]ce7d0cbc2013-05-03 18:57:229422 SpawnedTestServer::SSLOptions ssl_options(
9423 SpawnedTestServer::SSLOptions::CERT_AUTO);
9424 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029425 SSLConfigService::SetCRLSet(
9426 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9427
[email protected]51523f52013-07-31 21:57:289428 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129429 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029430
[email protected]51523f52013-07-31 21:57:289431 // Even with a fresh CRLSet, we should still do online revocation checks when
9432 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9433 // test.
9434 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9435 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029436
[email protected]51523f52013-07-31 21:57:289437 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029438 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289439 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029440}
9441
[email protected]b6f2de32012-08-17 04:35:089442TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9443 // Test that when EV verification is requested, but online revocation
9444 // checking is disabled, and the leaf certificate is not in fact EV, that
9445 // no revocation checking actually happens.
9446 if (!SystemSupportsOCSP()) {
9447 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9448 return;
9449 }
9450
9451 // Unmark the certificate's OID as EV, which should disable revocation
9452 // checking (as per the user preference)
9453 ev_test_policy_.reset();
9454
[email protected]ce7d0cbc2013-05-03 18:57:229455 SpawnedTestServer::SSLOptions ssl_options(
9456 SpawnedTestServer::SSLOptions::CERT_AUTO);
9457 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089458 SSLConfigService::SetCRLSet(
9459 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9460
9461 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129462 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:089463
9464 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9465
9466 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9467 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9468}
9469
[email protected]a13234c2012-03-20 21:45:029470class HTTPSCRLSetTest : public HTTPSOCSPTest {
9471 protected:
dchengb03027d2014-10-21 12:00:209472 void SetupContext(URLRequestContext* context) override {
nharperb7441ef2016-01-25 23:54:149473 context->set_ssl_config_service(new TestSSLConfigService(
9474 false /* check for EV */, false /* online revocation checking */,
9475 false /* require rev. checking for local
9476 anchors */,
9477 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029478 }
9479};
9480
9481TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229482 SpawnedTestServer::SSLOptions ssl_options(
9483 SpawnedTestServer::SSLOptions::CERT_AUTO);
9484 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029485 SSLConfigService::SetCRLSet(
9486 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9487
[email protected]924e9f92012-12-16 22:00:539488 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129489 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029490
9491 // If we're not trying EV verification then, even if the CRLSet has expired,
9492 // we don't fall back to online revocation checks.
9493 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9494 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9495 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9496}
[email protected]51523f52013-07-31 21:57:289497
9498TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309499#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289500 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9501 return;
9502#endif
9503
9504 SpawnedTestServer::SSLOptions ssl_options(
9505 SpawnedTestServer::SSLOptions::CERT_AUTO);
9506 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9507 ssl_options.cert_serial = 10;
9508 SSLConfigService::SetCRLSet(
9509 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9510 false, &kOCSPTestCertSPKI, "\x0a")));
9511
9512 CertStatus cert_status = 0;
9513 DoConnection(ssl_options, &cert_status);
9514
9515 // If the certificate is recorded as revoked in the CRLSet, that should be
9516 // reflected without online revocation checking.
9517 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9518 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9519 EXPECT_FALSE(
9520 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9521}
[email protected]316c1e5e2012-09-12 15:17:449522#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279523
mmenke9f2ec60c2015-06-01 20:59:479524#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9525// These tests aren't passing on Android. Either the RemoteTestServer isn't
9526// starting up successfully, or it can't access the test files.
9527// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319528class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119529 public:
[email protected]d9fca99a2012-02-24 16:16:209530 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:479531 : ftp_transaction_factory_(&host_resolver_),
tommycli59a63432015-11-06 00:10:559532 ftp_test_server_(SpawnedTestServer::TYPE_FTP,
9533 SpawnedTestServer::kLocalhost,
9534 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:479535 // Can't use |default_context_|'s HostResolver to set up the
9536 // FTPTransactionFactory because it hasn't been created yet.
9537 default_context_.set_host_resolver(&host_resolver_);
9538 }
9539
9540 // URLRequestTest interface:
9541 void SetUpFactory() override {
9542 // Add FTP support to the default URLRequestContext.
9543 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:209544 "ftp",
9545 make_scoped_ptr(new FtpProtocolHandler(&ftp_transaction_factory_)));
mmenke9f2ec60c2015-06-01 20:59:479546 }
9547
9548 std::string GetTestFileContents() {
9549 base::FilePath path;
9550 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9551 path = path.Append(kTestFilePath);
9552 path = path.AppendASCII(kFtpTestFile);
9553 std::string contents;
9554 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9555 return contents;
[email protected]95409e12010-08-17 20:07:119556 }
9557
[email protected]b89ca032009-08-31 21:41:319558 protected:
mmenke9f2ec60c2015-06-01 20:59:479559 MockHostResolver host_resolver_;
9560 FtpNetworkLayer ftp_transaction_factory_;
9561
tommycli59a63432015-11-06 00:10:559562 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:319563};
9564
[email protected]d2a133182012-08-05 16:44:089565// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099566TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089567 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089568
9569 TestDelegate d;
9570 {
davidben151423e2015-03-23 18:48:369571 scoped_ptr<URLRequest> r(
9572 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199573 r->Start();
9574 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089575
[email protected]255620da2013-08-19 13:14:299576 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089577
[email protected]f7022f32014-08-21 16:32:199578 EXPECT_FALSE(r->is_pending());
9579 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
9580 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:089581 }
9582}
9583
mmenke9f2ec60c2015-06-01 20:59:479584TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:559585 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119586
[email protected]a25e90e2009-09-09 17:05:379587 TestDelegate d;
9588 {
[email protected]f7022f32014-08-21 16:32:199589 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559590 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199591 r->Start();
9592 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379593
[email protected]255620da2013-08-19 13:14:299594 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379595
[email protected]f7022f32014-08-21 16:32:199596 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379597 EXPECT_EQ(1, d.response_started_count());
9598 EXPECT_FALSE(d.received_data_before_response());
9599 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:559600 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199601 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559602 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199603 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379604 }
9605}
9606
mmenke9f2ec60c2015-06-01 20:59:479607TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:559608 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119609
[email protected]dd265012009-01-08 20:45:279610 TestDelegate d;
9611 {
[email protected]f7022f32014-08-21 16:32:199612 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559613 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199614 r->Start();
9615 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279616
[email protected]255620da2013-08-19 13:14:299617 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279618
[email protected]f7022f32014-08-21 16:32:199619 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279620 EXPECT_EQ(1, d.response_started_count());
9621 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479622 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559623 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199624 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559625 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199626 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279627 }
9628}
9629
mmenke9f2ec60c2015-06-01 20:59:479630TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:559631 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119632
[email protected]dd265012009-01-08 20:45:279633 TestDelegate d;
9634 {
tommycli59a63432015-11-06 00:10:559635 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9636 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9637 "chrome"),
9638 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199639 r->Start();
9640 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279641
[email protected]255620da2013-08-19 13:14:299642 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279643
[email protected]f7022f32014-08-21 16:32:199644 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479645 EXPECT_EQ(1, d.response_started_count());
9646 EXPECT_FALSE(d.received_data_before_response());
9647 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559648 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199649 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559650 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199651 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:259652
9653 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:199654 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:259655 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:279656 }
9657}
9658
mmenke9f2ec60c2015-06-01 20:59:479659TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:559660 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119661
[email protected]dd265012009-01-08 20:45:279662 TestDelegate d;
9663 {
[email protected]f7022f32014-08-21 16:32:199664 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559665 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9666 "wrong_password"),
davidben151423e2015-03-23 18:48:369667 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199668 r->Start();
9669 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279670
[email protected]255620da2013-08-19 13:14:299671 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279672
[email protected]f7022f32014-08-21 16:32:199673 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279674 EXPECT_EQ(1, d.response_started_count());
9675 EXPECT_FALSE(d.received_data_before_response());
9676 EXPECT_EQ(d.bytes_received(), 0);
9677 }
9678}
9679
mmenke9f2ec60c2015-06-01 20:59:479680TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:559681 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119682
[email protected]8b8a197d2009-08-26 15:57:589683 TestDelegate d;
9684 // Set correct login credentials. The delegate will be asked for them when
9685 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589686 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589687 {
[email protected]f7022f32014-08-21 16:32:199688 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559689 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9690 "wrong_password"),
davidben151423e2015-03-23 18:48:369691 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199692 r->Start();
9693 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589694
[email protected]255620da2013-08-19 13:14:299695 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589696
[email protected]f7022f32014-08-21 16:32:199697 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589698 EXPECT_EQ(1, d.response_started_count());
9699 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479700 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589701 }
9702}
9703
mmenke9f2ec60c2015-06-01 20:59:479704TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:559705 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119706
[email protected]dd265012009-01-08 20:45:279707 TestDelegate d;
9708 {
mmenke9f2ec60c2015-06-01 20:59:479709 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559710 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9711 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479712 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199713 r->Start();
9714 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279715
[email protected]255620da2013-08-19 13:14:299716 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279717
[email protected]f7022f32014-08-21 16:32:199718 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279719 EXPECT_EQ(1, d.response_started_count());
9720 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479721 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279722 }
9723}
[email protected]8b8a197d2009-08-26 15:57:589724
mmenke9f2ec60c2015-06-01 20:59:479725TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:559726 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119727
[email protected]8b8a197d2009-08-26 15:57:589728 TestDelegate d;
9729 // Set correct login credentials. The delegate will be asked for them when
9730 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589731 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589732 {
mmenke9f2ec60c2015-06-01 20:59:479733 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559734 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9735 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479736 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199737 r->Start();
9738 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589739
[email protected]255620da2013-08-19 13:14:299740 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589741
[email protected]f7022f32014-08-21 16:32:199742 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589743 EXPECT_EQ(1, d.response_started_count());
9744 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479745 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589746 }
9747}
[email protected]60a3df52009-09-22 16:13:249748
mmenke9f2ec60c2015-06-01 20:59:479749TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:559750 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119751
[email protected]60a3df52009-09-22 16:13:249752 scoped_ptr<TestDelegate> d(new TestDelegate);
9753 {
9754 // Pass correct login identity in the URL.
tommycli59a63432015-11-06 00:10:559755 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9756 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9757 "chrome"),
9758 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199759 r->Start();
9760 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249761
[email protected]255620da2013-08-19 13:14:299762 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249763
[email protected]f7022f32014-08-21 16:32:199764 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249765 EXPECT_EQ(1, d->response_started_count());
9766 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479767 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249768 }
9769
9770 d.reset(new TestDelegate);
9771 {
9772 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199773 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559774 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199775 r->Start();
9776 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249777
[email protected]255620da2013-08-19 13:14:299778 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249779
[email protected]f7022f32014-08-21 16:32:199780 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249781 EXPECT_EQ(1, d->response_started_count());
9782 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479783 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249784 }
9785}
9786
mmenke9f2ec60c2015-06-01 20:59:479787TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:559788 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119789
[email protected]60a3df52009-09-22 16:13:249790 scoped_ptr<TestDelegate> d(new TestDelegate);
9791 // Set correct login credentials. The delegate will be asked for them when
9792 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589793 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249794 {
[email protected]f7022f32014-08-21 16:32:199795 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559796 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9797 "wrong_password"),
davidben151423e2015-03-23 18:48:369798 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199799 r->Start();
9800 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249801
[email protected]255620da2013-08-19 13:14:299802 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249803
[email protected]f7022f32014-08-21 16:32:199804 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249805 EXPECT_EQ(1, d->response_started_count());
9806 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479807 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249808 }
9809
9810 // Use a new delegate without explicit credentials. The cached ones should be
9811 // used.
9812 d.reset(new TestDelegate);
9813 {
9814 // Don't pass wrong credentials in the URL, they would override valid cached
9815 // ones.
[email protected]f7022f32014-08-21 16:32:199816 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559817 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199818 r->Start();
9819 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249820
[email protected]255620da2013-08-19 13:14:299821 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249822
[email protected]f7022f32014-08-21 16:32:199823 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249824 EXPECT_EQ(1, d->response_started_count());
9825 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479826 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249827 }
9828}
[email protected]316c1e5e2012-09-12 15:17:449829#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519830
ttuttlec0c828492015-05-15 01:25:559831TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9832 TestDelegate d;
9833 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9834 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9835 d.set_quit_on_network_start(true);
9836
9837 EXPECT_FALSE(req->response_info().network_accessed);
9838
9839 req->Start();
9840 base::RunLoop().Run();
9841
9842 EXPECT_EQ(1, d.received_before_network_start_count());
9843 EXPECT_EQ(0, d.response_started_count());
9844 EXPECT_FALSE(req->response_info().network_accessed);
9845
9846 req->ResumeNetworkStart();
9847 base::RunLoop().Run();
9848}
9849
9850TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9851 TestDelegate d;
9852 scoped_ptr<URLRequest> req(
9853 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9854
9855 EXPECT_FALSE(req->response_info().network_accessed);
9856
9857 req->Start();
9858 base::RunLoop().Run();
9859
9860 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9861 EXPECT_FALSE(req->response_info().network_accessed);
9862}
9863
9864TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9865 MockHostResolver host_resolver;
9866 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9867 TestURLRequestContext context(true);
9868 context.set_network_delegate(&network_delegate);
9869 context.set_host_resolver(&host_resolver);
9870 host_resolver.rules()->AddSimulatedFailure("*");
9871 context.Init();
9872
9873 TestDelegate d;
9874 scoped_ptr<URLRequest> req(context.CreateRequest(
9875 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9876
9877 EXPECT_FALSE(req->response_info().network_accessed);
9878
9879 req->Start();
9880 base::RunLoop().Run();
9881 EXPECT_TRUE(req->response_info().network_accessed);
9882}
9883
mmenkeed0498b2015-12-08 23:20:429884// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:229885// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:429886TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:229887 TestDelegate d;
9888 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9889 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
9890
mmenkeed0498b2015-12-08 23:20:429891 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:229892 req.get(), &default_network_delegate_,
9893 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:429894 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
9895 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:229896
9897 req->Start();
9898 req->Cancel();
alexanderkcd904b52015-07-24 18:57:229899 base::RunLoop().RunUntilIdle();
9900 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
9901 EXPECT_EQ(0, d.received_redirect_count());
9902}
9903
[email protected]7461a402011-03-24 23:19:519904} // namespace net