blob: 78e4eb30f79a551bd290dece245ee35ce7afeafb [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
mkwst3f3daac2015-02-26 20:15:262653TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2654 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
mkwst3f3daac2015-02-26 20:15:262661 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2662 // LocalHttpTestServer points).
2663 {
mkwst3f3daac2015-02-26 20:15:262664 TestDelegate d;
2665 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2666 test_server.GetURL(
tommycli59a63432015-11-06 00:10:552667 "/set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
davidben151423e2015-03-23 18:48:362668 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262669 req->Start();
2670 base::RunLoop().Run();
2671 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2672 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2673 EXPECT_EQ(1, network_delegate.set_cookie_count());
2674 }
2675
2676 // Verify that the cookie is sent for first-party requests.
2677 {
mkwst3f3daac2015-02-26 20:15:262678 TestDelegate d;
2679 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552680 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2681 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst202534e32016-01-15 16:07:152682 req->set_initiator(url::Origin(test_server.GetURL("/")));
mkwst3f3daac2015-02-26 20:15:262683 req->Start();
2684 base::RunLoop().Run();
2685
2686 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2687 std::string::npos);
2688 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2689 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2690 }
2691
mkwst202534e32016-01-15 16:07:152692 // Verify that the cookie is not sent for non-first-party requests.
mkwst3f3daac2015-02-26 20:15:262693 {
mkwst3f3daac2015-02-26 20:15:262694 TestDelegate d;
2695 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552696 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262697 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
mkwst202534e32016-01-15 16:07:152698 req->set_initiator(url::Origin(GURL("http://third-party.test/")));
2699 req->Start();
2700 base::RunLoop().Run();
2701
2702 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2703 std::string::npos);
2704 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2705 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2706 }
2707
2708 // Verify that the cookie is sent for non-first-party initiators when the
2709 // method is "safe".
2710 {
2711 TestDelegate d;
2712 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2713 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2714 req->set_first_party_for_cookies(test_server.GetURL("/"));
2715 req->set_initiator(url::Origin(GURL("http://third-party.test/")));
2716 req->Start();
2717 base::RunLoop().Run();
2718
2719 EXPECT_FALSE(d.data_received().find("FirstPartyCookieToSet=1") ==
2720 std::string::npos);
2721 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2722 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2723 }
2724
2725 // Verify that the cookie is not sent for non-first-party initiators when the
2726 // method is unsafe (e.g. POST).
2727 {
2728 TestDelegate d;
2729 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2730 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2731 req->set_first_party_for_cookies(test_server.GetURL("/"));
2732 req->set_initiator(url::Origin(GURL("http://third-party.test/")));
2733 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:262734 req->Start();
2735 base::RunLoop().Run();
2736
2737 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2738 std::string::npos);
2739 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2740 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2741 }
2742}
2743
mkwst0513c9d2015-04-01 05:53:152744TEST_F(URLRequestTest, FirstPartyOnlyCookiesDisabled) {
2745 LocalHttpTestServer test_server;
2746 ASSERT_TRUE(test_server.Start());
2747
2748 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2749 // LocalHttpTestServer points).
2750 {
2751 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412752 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152753 default_context_.set_network_delegate(&network_delegate);
2754
2755 TestDelegate d;
2756 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2757 test_server.GetURL(
tommycli59a63432015-11-06 00:10:552758 "/set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
mkwst0513c9d2015-04-01 05:53:152759 DEFAULT_PRIORITY, &d));
2760 req->Start();
2761 base::RunLoop().Run();
2762 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2763 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2764 EXPECT_EQ(1, network_delegate.set_cookie_count());
2765 }
2766
2767 // Verify that the cookie is sent for first-party requests.
2768 {
2769 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412770 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152771 default_context_.set_network_delegate(&network_delegate);
2772 TestDelegate d;
2773 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552774 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2775 req->set_first_party_for_cookies(test_server.GetURL("/"));
mkwst0513c9d2015-04-01 05:53:152776 req->Start();
2777 base::RunLoop().Run();
2778
2779 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2780 std::string::npos);
2781 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2782 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2783 }
2784
2785 // Verify that the cookie is also sent for non-first-party requests.
2786 {
2787 TestNetworkDelegate network_delegate;
estark7625d812015-10-12 20:10:412788 network_delegate.set_experimental_cookie_features_enabled(false);
mkwst0513c9d2015-04-01 05:53:152789 default_context_.set_network_delegate(&network_delegate);
2790 TestDelegate d;
2791 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552792 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst0513c9d2015-04-01 05:53:152793 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2794 req->Start();
2795 base::RunLoop().Run();
2796
jww79aceda2015-12-07 01:56:342797 EXPECT_NE(d.data_received().find("FirstPartyCookieToSet=1"),
2798 std::string::npos);
mkwst0513c9d2015-04-01 05:53:152799 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2800 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2801 }
2802}
2803
estark557a5eb82015-12-01 22:57:102804// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:362805TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:552806 EmbeddedTestServer http_server;
2807 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362808 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552809 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2810 https_server.AddDefaultHandlers(
2811 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2812 ASSERT_TRUE(http_server.Start());
2813 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362814
estarkb15166b2015-12-18 16:56:382815 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362816 TestURLRequestContext context(true);
2817 context.set_network_delegate(&network_delegate);
2818 context.Init();
2819
estarkb15166b2015-12-18 16:56:382820 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362821 {
2822 TestDelegate d;
2823 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102824 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362825 DEFAULT_PRIORITY, &d));
2826 req->Start();
2827 base::RunLoop().Run();
2828 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2829 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2830 }
2831
2832 // Verify that the cookie is not set.
2833 {
2834 TestDelegate d;
2835 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552836 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362837 req->Start();
2838 base::RunLoop().Run();
2839
jww79aceda2015-12-07 01:56:342840 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
2841 std::string::npos);
estarkcd39c11f2015-10-19 19:46:362842 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2843 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2844 }
2845}
2846
estarkb15166b2015-12-18 16:56:382847TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:552848 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2849 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362850 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552851 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362852
2853 TestNetworkDelegate network_delegate;
2854 TestURLRequestContext context(true);
2855 context.set_network_delegate(&network_delegate);
2856 context.Init();
2857
estarkb15166b2015-12-18 16:56:382858 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362859 {
2860 TestDelegate d;
tommycli59a63432015-11-06 00:10:552861 scoped_ptr<URLRequest> req(
estark557a5eb82015-12-01 22:57:102862 context.CreateRequest(https_server.GetURL("/set-cookie?__Secure-foo=1"),
tommycli59a63432015-11-06 00:10:552863 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362864 req->Start();
2865 base::RunLoop().Run();
2866 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2867 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2868 }
2869
2870 // Verify that the cookie is not set.
2871 {
2872 TestDelegate d;
2873 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552874 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362875 req->Start();
2876 base::RunLoop().Run();
2877
jww79aceda2015-12-07 01:56:342878 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362879 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2880 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2881 }
2882}
2883
estarkb15166b2015-12-18 16:56:382884TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:552885 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2886 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362887 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552888 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362889
estarkb15166b2015-12-18 16:56:382890 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362891 TestURLRequestContext context(true);
2892 context.set_network_delegate(&network_delegate);
2893 context.Init();
2894
estarkb15166b2015-12-18 16:56:382895 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362896 {
2897 TestDelegate d;
2898 scoped_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102899 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
tommycli59a63432015-11-06 00:10:552900 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362901 req->Start();
2902 base::RunLoop().Run();
2903 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2904 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2905 }
2906
2907 // Verify that the cookie is set.
2908 {
2909 TestDelegate d;
2910 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552911 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362912 req->Start();
2913 base::RunLoop().Run();
2914
jww79aceda2015-12-07 01:56:342915 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
2916 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2917 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2918 }
2919}
2920
2921// Tests that secure cookies can't be set on non-secure origins if strict secure
2922// cookies are enabled.
2923TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
2924 EmbeddedTestServer http_server;
2925 http_server.AddDefaultHandlers(
2926 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2927 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2928 https_server.AddDefaultHandlers(
2929 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2930 ASSERT_TRUE(http_server.Start());
2931 ASSERT_TRUE(https_server.Start());
2932
2933 TestExperimentalFeaturesNetworkDelegate network_delegate;
2934 TestURLRequestContext context(true);
2935 context.set_network_delegate(&network_delegate);
2936 context.Init();
2937
2938 // Try to set a Secure cookie, with experimental features enabled.
2939 {
2940 TestDelegate d;
2941 scoped_ptr<URLRequest> req(context.CreateRequest(
2942 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
2943 DEFAULT_PRIORITY, &d));
2944 req->Start();
2945 base::RunLoop().Run();
2946 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2947 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2948 }
2949
2950 // Verify that the cookie is not set.
2951 {
2952 TestDelegate d;
2953 scoped_ptr<URLRequest> req(context.CreateRequest(
2954 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2955 req->Start();
2956 base::RunLoop().Run();
2957
2958 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
2959 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2960 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2961 }
2962}
2963
2964// Tests that secure cookies can be set on secure origins even if strict secure
2965// cookies are enabled.
2966TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
2967 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2968 https_server.AddDefaultHandlers(
2969 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2970 ASSERT_TRUE(https_server.Start());
2971
2972 TestExperimentalFeaturesNetworkDelegate network_delegate;
2973 TestURLRequestContext context(true);
2974 context.set_network_delegate(&network_delegate);
2975 context.Init();
2976
2977 // Try to set a Secure cookie, with experimental features enabled.
2978 {
2979 TestDelegate d;
2980 scoped_ptr<URLRequest> req(context.CreateRequest(
2981 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
2982 DEFAULT_PRIORITY, &d));
2983 req->Start();
2984 base::RunLoop().Run();
2985 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2986 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2987 }
2988
2989 // Verify that the cookie is not set.
2990 {
2991 TestDelegate d;
2992 scoped_ptr<URLRequest> req(context.CreateRequest(
2993 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2994 req->Start();
2995 base::RunLoop().Run();
2996
2997 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362998 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2999 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3000 }
3001}
3002
mmenkefb18c772015-09-30 22:22:503003// Tests that a request is cancelled while entering suspend mode. Uses mocks
3004// rather than a spawned test server because the connection used to talk to
3005// the test server is affected by entering suspend mode on Android.
3006TEST_F(URLRequestTest, CancelOnSuspend) {
3007 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
3008 base::PowerMonitor power_monitor(make_scoped_ptr(power_monitor_source));
3009
3010 URLRequestFailedJob::AddUrlHandler();
3011
3012 TestDelegate d;
3013 // Request that just hangs.
3014 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
3015 scoped_ptr<URLRequest> r(
3016 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
3017 r->Start();
3018
3019 power_monitor_source->Suspend();
3020 // Wait for the suspend notification to cause the request to fail.
3021 base::RunLoop().Run();
3022 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3023 EXPECT_TRUE(d.request_failed());
3024 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3025
3026 URLRequestFilter::GetInstance()->ClearHandlers();
3027
3028 // Shouldn't be needed, but just in case.
3029 power_monitor_source->Resume();
3030}
3031
[email protected]5095cd72012-11-01 10:29:163032// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3033// value for the |fixed_date| argument given to the constructor.
3034class FixedDateNetworkDelegate : public TestNetworkDelegate {
3035 public:
3036 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3037 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:203038 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163039
[email protected]cba24642014-08-15 20:49:593040 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203041 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593042 URLRequest* request,
3043 const CompletionCallback& callback,
3044 const HttpResponseHeaders* original_response_headers,
3045 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133046 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163047
3048 private:
3049 std::string fixed_date_;
3050
3051 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3052};
3053
3054int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593055 URLRequest* request,
3056 const CompletionCallback& callback,
3057 const HttpResponseHeaders* original_response_headers,
3058 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163059 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593060 HttpResponseHeaders* new_response_headers =
3061 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163062
3063 new_response_headers->RemoveHeader("Date");
3064 new_response_headers->AddHeader("Date: " + fixed_date_);
3065
3066 *override_response_headers = new_response_headers;
3067 return TestNetworkDelegate::OnHeadersReceived(request,
3068 callback,
3069 original_response_headers,
[email protected]5f714132014-03-26 10:41:163070 override_response_headers,
3071 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163072}
3073
3074// Test that cookie expiration times are adjusted for server/client clock
3075// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3076// headers by defaulting to GMT. (crbug.com/135131)
3077TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3078 LocalHttpTestServer test_server;
3079 ASSERT_TRUE(test_server.Start());
3080
3081 // Set up an expired cookie.
3082 {
3083 TestNetworkDelegate network_delegate;
3084 default_context_.set_network_delegate(&network_delegate);
3085 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193086 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193087 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553088 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363089 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193090 req->Start();
[email protected]255620da2013-08-19 13:14:293091 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163092 }
3093 // Verify that the cookie is not set.
3094 {
3095 TestNetworkDelegate network_delegate;
3096 default_context_.set_network_delegate(&network_delegate);
3097 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193098 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553099 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193100 req->Start();
[email protected]255620da2013-08-19 13:14:293101 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163102
3103 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3104 }
3105 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3106 {
3107 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3108 default_context_.set_network_delegate(&network_delegate);
3109 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193110 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193111 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553112 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363113 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193114 req->Start();
[email protected]255620da2013-08-19 13:14:293115 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163116 }
3117 // Verify that the cookie is set.
3118 {
3119 TestNetworkDelegate network_delegate;
3120 default_context_.set_network_delegate(&network_delegate);
3121 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193122 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553123 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193124 req->Start();
[email protected]255620da2013-08-19 13:14:293125 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163126
3127 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3128 }
3129}
3130
3131
[email protected]316c1e5e2012-09-12 15:17:443132// Check that it is impossible to change the referrer in the extra headers of
3133// an URLRequest.
3134TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3135 LocalHttpTestServer test_server;
3136 ASSERT_TRUE(test_server.Start());
3137
3138 // If extra headers contain referer and the request contains a referer,
3139 // only the latter shall be respected.
3140 {
3141 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193142 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553143 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193144 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443145
3146 HttpRequestHeaders headers;
3147 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193148 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443149
[email protected]f7022f32014-08-21 16:32:193150 req->Start();
[email protected]255620da2013-08-19 13:14:293151 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443152
3153 EXPECT_EQ("http://foo.com/", d.data_received());
3154 }
3155
3156 // If extra headers contain a referer but the request does not, no referer
3157 // shall be sent in the header.
3158 {
3159 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193160 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553161 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443162
3163 HttpRequestHeaders headers;
3164 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193165 req->SetExtraRequestHeaders(headers);
3166 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443167
[email protected]f7022f32014-08-21 16:32:193168 req->Start();
[email protected]255620da2013-08-19 13:14:293169 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443170
3171 EXPECT_EQ("None", d.data_received());
3172 }
3173}
3174
[email protected]b89290212009-08-14 22:37:353175class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113176 public:
mmenke9f2ec60c2015-06-01 20:59:473177 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113178
[email protected]b89290212009-08-14 22:37:353179 protected:
[email protected]21184962011-10-26 00:50:303180 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3181 // |request_method| is the method to use for the initial request.
3182 // |redirect_method| is the method that is expected to be used for the second
3183 // request, after redirection.
3184 // If |include_data| is true, data is uploaded with the request. The
3185 // response body is expected to match it exactly, if and only if
3186 // |request_method| == |redirect_method|.
3187 void HTTPRedirectMethodTest(const GURL& redirect_url,
3188 const std::string& request_method,
3189 const std::string& redirect_method,
3190 bool include_data) {
3191 static const char kData[] = "hello world";
3192 TestDelegate d;
davidben151423e2015-03-23 18:48:363193 scoped_ptr<URLRequest> req(
3194 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193195 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303196 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073197 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303198 HttpRequestHeaders headers;
3199 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513200 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543201 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193202 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303203 }
[email protected]f7022f32014-08-21 16:32:193204 req->Start();
[email protected]255620da2013-08-19 13:14:293205 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193206 EXPECT_EQ(redirect_method, req->method());
3207 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
3208 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:303209 if (include_data) {
3210 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543211 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3212 HttpRequestHeaders::kContentLength));
3213 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3214 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303215 EXPECT_EQ(kData, d.data_received());
3216 } else {
svaldez5b3a8972015-10-09 23:23:543217 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3218 HttpRequestHeaders::kContentLength));
3219 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3220 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303221 EXPECT_NE(kData, d.data_received());
3222 }
3223 }
3224 if (HasFailure())
3225 LOG(WARNING) << "Request method was: " << request_method;
3226 }
3227
jww5fe460ff2015-03-28 00:22:513228 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3229 // |request_method| is the method to use for the initial request.
3230 // |redirect_method| is the method that is expected to be used for the second
3231 // request, after redirection.
3232 // |origin_value| is the expected value for the Origin header after
3233 // redirection. If empty, expects that there will be no Origin header.
3234 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3235 const std::string& request_method,
3236 const std::string& redirect_method,
3237 const std::string& origin_value) {
3238 TestDelegate d;
3239 scoped_ptr<URLRequest> req(
3240 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3241 req->set_method(request_method);
3242 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3243 redirect_url.GetOrigin().spec(), false);
3244 req->Start();
3245
3246 base::RunLoop().Run();
3247
3248 EXPECT_EQ(redirect_method, req->method());
3249 // Note that there is no check for request success here because, for
3250 // purposes of testing, the request very well may fail. For example, if the
3251 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3252 // origin, there is not an HTTPS server in this unit test framework, so the
3253 // request would fail. However, that's fine, as long as the request headers
3254 // are in order and pass the checks below.
3255 if (origin_value.empty()) {
3256 EXPECT_FALSE(
3257 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3258 } else {
3259 std::string origin_header;
3260 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3261 HttpRequestHeaders::kOrigin, &origin_header));
3262 EXPECT_EQ(origin_value, origin_header);
3263 }
3264 }
3265
[email protected]762d2db2010-01-11 19:03:013266 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013267 const int kMsgSize = 20000; // multiple of 10
3268 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483269 char* uploadBytes = new char[kMsgSize+1];
3270 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013271 char marker = 'a';
3272 for (int idx = 0; idx < kMsgSize/10; idx++) {
3273 memcpy(ptr, "----------", 10);
3274 ptr += 10;
3275 if (idx % 100 == 0) {
3276 ptr--;
3277 *ptr++ = marker;
3278 if (++marker > 'z')
3279 marker = 'a';
3280 }
3281 }
3282 uploadBytes[kMsgSize] = '\0';
3283
[email protected]762d2db2010-01-11 19:03:013284 for (int i = 0; i < kIterations; ++i) {
3285 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193286 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553287 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193288 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013289
mmenkecbc2b712014-10-09 20:29:073290 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013291
[email protected]f7022f32014-08-21 16:32:193292 r->Start();
3293 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013294
[email protected]255620da2013-08-19 13:14:293295 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013296
[email protected]329b68b2012-11-14 17:54:273297 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:193298 << "request failed: " << r->status().status()
3299 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:013300
3301 EXPECT_FALSE(d.received_data_before_response());
3302 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013303 }
3304 delete[] uploadBytes;
3305 }
3306
[email protected]ef2bf422012-05-11 03:27:093307 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:223308 r->AppendChunkToUpload("a", 1, false);
3309 r->AppendChunkToUpload("bcd", 3, false);
3310 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
3311 r->AppendChunkToUpload("\r\n\r\n", 4, false);
3312 r->AppendChunkToUpload("0", 1, false);
3313 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:113314 }
3315
[email protected]ef2bf422012-05-11 03:27:093316 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:113317 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:273318 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:113319 "abcdthis is a longer chunk than before.\r\n\r\n02323";
3320
[email protected]329b68b2012-11-14 17:54:273321 ASSERT_EQ(1, d->response_started_count())
3322 << "request failed: " << r->status().status()
3323 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:113324
3325 EXPECT_FALSE(d->received_data_before_response());
3326
[email protected]329b68b2012-11-14 17:54:273327 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
3328 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:113329 }
3330
[email protected]ede03212012-09-07 12:52:263331 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343332 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193333 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553334 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363335 base::IntToString(num_cookies)),
3336 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343337
[email protected]f7022f32014-08-21 16:32:193338 r->Start();
3339 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343340
[email protected]255620da2013-08-19 13:14:293341 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343342
[email protected]f7022f32014-08-21 16:32:193343 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:343344
tommycli59a63432015-11-06 00:10:553345 if (!is_success)
[email protected]f7022f32014-08-21 16:32:193346 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:343347
3348 return is_success;
3349 }
3350
tommycli59a63432015-11-06 00:10:553351 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503352
tommycli59a63432015-11-06 00:10:553353 private:
[email protected]1700c6a2012-02-22 18:07:073354 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353355};
3356
tommycli59a63432015-11-06 00:10:553357namespace {
3358
3359scoped_ptr<test_server::HttpResponse> HandleRedirectConnect(
3360 const test_server::HttpRequest& request) {
3361 if (request.headers.find("Host") == request.headers.end() ||
3362 request.headers.at("Host") != "www.redirect.com" ||
3363 request.method != test_server::METHOD_CONNECT) {
3364 return nullptr;
3365 }
3366
3367 scoped_ptr<test_server::BasicHttpResponse> http_response(
3368 new test_server::BasicHttpResponse);
3369 http_response->set_code(HTTP_FOUND);
3370 http_response->AddCustomHeader("Location",
3371 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:483372 return std::move(http_response);
tommycli59a63432015-11-06 00:10:553373}
3374
3375} // namespace
3376
nharperb7441ef2016-01-25 23:54:143377class TestSSLConfigService : public SSLConfigService {
3378 public:
3379 TestSSLConfigService(bool ev_enabled,
3380 bool online_rev_checking,
3381 bool rev_checking_required_local_anchors,
3382 bool token_binding_enabled)
3383 : ev_enabled_(ev_enabled),
3384 online_rev_checking_(online_rev_checking),
3385 rev_checking_required_local_anchors_(
3386 rev_checking_required_local_anchors),
3387 token_binding_enabled_(token_binding_enabled),
3388 min_version_(kDefaultSSLVersionMin),
3389 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
3390
3391 void set_min_version(uint16_t version) { min_version_ = version; }
3392
3393 void set_fallback_min_version(uint16_t version) {
3394 fallback_min_version_ = version;
3395 }
3396
3397 // SSLConfigService:
3398 void GetSSLConfig(SSLConfig* config) override {
3399 *config = SSLConfig();
3400 config->rev_checking_enabled = online_rev_checking_;
3401 config->verify_ev_cert = ev_enabled_;
3402 config->rev_checking_required_local_anchors =
3403 rev_checking_required_local_anchors_;
3404 if (fallback_min_version_) {
3405 config->version_fallback_min = fallback_min_version_;
3406 }
3407 if (min_version_) {
3408 config->version_min = min_version_;
3409 }
3410 if (token_binding_enabled_) {
3411 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
3412 }
3413 }
3414
3415 protected:
3416 ~TestSSLConfigService() override {}
3417
3418 private:
3419 const bool ev_enabled_;
3420 const bool online_rev_checking_;
3421 const bool rev_checking_required_local_anchors_;
3422 const bool token_binding_enabled_;
3423 uint16_t min_version_;
3424 uint16_t fallback_min_version_;
3425};
3426
3427// TODO(svaldez): Update tests to use EmbeddedTestServer.
3428#if !defined(OS_IOS)
3429class TokenBindingURLRequestTest : public URLRequestTestHTTP {
3430 public:
3431 void SetUp() override {
3432 default_context_.set_ssl_config_service(
3433 new TestSSLConfigService(false, false, false, true));
3434 channel_id_service_.reset(new ChannelIDService(
3435 new DefaultChannelIDStore(NULL), base::ThreadTaskRunnerHandle::Get()));
3436 default_context_.set_channel_id_service(channel_id_service_.get());
3437 URLRequestTestHTTP::SetUp();
3438 }
3439
3440 protected:
3441 scoped_ptr<ChannelIDService> channel_id_service_;
3442};
3443
3444TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
3445 SpawnedTestServer::SSLOptions ssl_options;
3446 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3447 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3448 ssl_options,
3449 base::FilePath(kTestFilePath));
3450 ASSERT_TRUE(https_test_server.Start());
3451
3452 TestDelegate d;
3453 {
3454 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3455 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d));
3456 r->Start();
3457 EXPECT_TRUE(r->is_pending());
3458
3459 base::RunLoop().Run();
3460
3461 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3462
3463 HttpRequestHeaders headers;
3464 std::string token_binding_header, token_binding_message;
3465 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3466 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3467 &token_binding_header));
3468 EXPECT_TRUE(base::Base64UrlDecode(
3469 token_binding_header, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
3470 &token_binding_message));
3471 base::StringPiece ec_point, signature;
3472 EXPECT_TRUE(
3473 ParseTokenBindingMessage(token_binding_message, &ec_point, &signature));
3474
3475 EXPECT_GT(d.bytes_received(), 0);
3476 std::string ekm = d.data_received();
3477
3478 EXPECT_TRUE(VerifyEKMSignature(ec_point, signature, ekm));
3479 }
3480}
3481#endif // !defined(OS_IOS)
3482
3483// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113484// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553485// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113486// follow.
[email protected]f2f31b32013-01-16 23:24:093487TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553488 http_test_server()->RegisterRequestHandler(
3489 base::Bind(&HandleRedirectConnect));
3490 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113491
[email protected]ceefd7fd2012-11-29 00:36:243492 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043493 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553494 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503495
[email protected]d1ec59082009-02-11 02:48:153496 TestDelegate d;
3497 {
[email protected]f7022f32014-08-21 16:32:193498 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363499 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193500 r->Start();
3501 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153502
[email protected]255620da2013-08-19 13:14:293503 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153504
[email protected]f7022f32014-08-21 16:32:193505 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153506 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193507 EXPECT_TRUE(r->proxy_server().IsEmpty());
3508 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083509 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153510 // We should not have followed the redirect.
3511 EXPECT_EQ(0, d.received_redirect_count());
3512 }
3513}
3514
[email protected]8202d0c2011-02-23 08:31:143515// This is the same as the previous test, but checks that the network delegate
3516// registers the error.
[email protected]c044616e2013-02-20 02:01:263517TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553518 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143519
[email protected]ceefd7fd2012-11-29 00:36:243520 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043521 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553522 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503523
[email protected]8202d0c2011-02-23 08:31:143524 TestDelegate d;
3525 {
[email protected]f7022f32014-08-21 16:32:193526 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363527 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193528 r->Start();
3529 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143530
[email protected]255620da2013-08-19 13:14:293531 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143532
[email protected]f7022f32014-08-21 16:32:193533 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153534 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193535 EXPECT_TRUE(r->proxy_server().IsEmpty());
3536 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143537 EXPECT_EQ(1, d.response_started_count());
3538 // We should not have followed the redirect.
3539 EXPECT_EQ(0, d.received_redirect_count());
3540
3541 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053542 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143543 }
3544}
3545
[email protected]dc5a5cf2012-09-26 02:49:303546// Tests that we can block and asynchronously return OK in various stages.
3547TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3548 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3549 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3550 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3551 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3552 };
3553 static const size_t blocking_stages_length = arraysize(blocking_stages);
3554
tommycli59a63432015-11-06 00:10:553555 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:303556
3557 TestDelegate d;
3558 BlockingNetworkDelegate network_delegate(
3559 BlockingNetworkDelegate::USER_CALLBACK);
3560 network_delegate.set_block_on(
3561 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3562 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3563 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3564
3565 TestURLRequestContext context(true);
3566 context.set_network_delegate(&network_delegate);
3567 context.Init();
3568
3569 {
[email protected]f7022f32014-08-21 16:32:193570 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553571 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303572
[email protected]f7022f32014-08-21 16:32:193573 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303574 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293575 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303576 EXPECT_EQ(blocking_stages[i],
3577 network_delegate.stage_blocked_for_callback());
3578 network_delegate.DoCallback(OK);
3579 }
[email protected]255620da2013-08-19 13:14:293580 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193581 EXPECT_EQ(200, r->GetResponseCode());
3582 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303583 EXPECT_EQ(1, network_delegate.created_requests());
3584 EXPECT_EQ(0, network_delegate.destroyed_requests());
3585 }
3586 EXPECT_EQ(1, network_delegate.destroyed_requests());
3587}
3588
[email protected]4c76d7c2011-04-15 19:14:123589// Tests that the network delegate can block and cancel a request.
3590TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:553591 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123592
3593 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303594 BlockingNetworkDelegate network_delegate(
3595 BlockingNetworkDelegate::AUTO_CALLBACK);
3596 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3597 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123598
[email protected]d5a4dd62012-05-23 01:41:043599 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553600 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503601
[email protected]4c76d7c2011-04-15 19:14:123602 {
[email protected]f7022f32014-08-21 16:32:193603 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553604 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123605
[email protected]f7022f32014-08-21 16:32:193606 r->Start();
[email protected]255620da2013-08-19 13:14:293607 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123608
[email protected]f7022f32014-08-21 16:32:193609 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153610 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193611 EXPECT_TRUE(r->proxy_server().IsEmpty());
3612 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123613 EXPECT_EQ(1, network_delegate.created_requests());
3614 EXPECT_EQ(0, network_delegate.destroyed_requests());
3615 }
3616 EXPECT_EQ(1, network_delegate.destroyed_requests());
3617}
3618
[email protected]b4438d32012-09-27 06:15:303619// Helper function for NetworkDelegateCancelRequestAsynchronously and
3620// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3621// delegate operating in |block_mode| and a request for |url|. It blocks the
3622// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3623void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3624 BlockingNetworkDelegate::Stage stage,
3625 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363626 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303627 BlockingNetworkDelegate network_delegate(block_mode);
3628 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3629 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363630
[email protected]b4438d32012-09-27 06:15:303631 TestURLRequestContext context(true);
3632 context.set_network_delegate(&network_delegate);
3633 context.Init();
[email protected]3cd384c602011-08-31 16:12:363634
3635 {
davidben151423e2015-03-23 18:48:363636 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363637
[email protected]f7022f32014-08-21 16:32:193638 r->Start();
[email protected]255620da2013-08-19 13:14:293639 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363640
[email protected]f7022f32014-08-21 16:32:193641 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153642 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193643 EXPECT_TRUE(r->proxy_server().IsEmpty());
3644 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363645 EXPECT_EQ(1, network_delegate.created_requests());
3646 EXPECT_EQ(0, network_delegate.destroyed_requests());
3647 }
3648 EXPECT_EQ(1, network_delegate.destroyed_requests());
3649}
3650
[email protected]b4438d32012-09-27 06:15:303651// The following 3 tests check that the network delegate can cancel a request
3652// synchronously in various stages of the request.
3653TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:553654 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303655 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3656 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553657 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303658}
3659
3660TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:553661 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303662 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3663 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553664 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303665}
3666
3667TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:553668 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303669 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3670 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553671 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303672}
3673
3674// The following 3 tests check that the network delegate can cancel a request
3675// asynchronously in various stages of the request.
3676TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:553677 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303678 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3679 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553680 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303681}
3682
3683TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:553684 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303685 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3686 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553687 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303688}
3689
3690TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:553691 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303692 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3693 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553694 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303695}
3696
[email protected]4c76d7c2011-04-15 19:14:123697// Tests that the network delegate can block and redirect a request to a new
3698// URL.
3699TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:553700 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123701
3702 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303703 BlockingNetworkDelegate network_delegate(
3704 BlockingNetworkDelegate::AUTO_CALLBACK);
3705 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553706 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:123707 network_delegate.set_redirect_url(redirect_url);
3708
[email protected]d5a4dd62012-05-23 01:41:043709 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553710 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503711
[email protected]4c76d7c2011-04-15 19:14:123712 {
tommycli59a63432015-11-06 00:10:553713 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363714 scoped_ptr<URLRequest> r(
3715 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123716
[email protected]6be6fa92014-08-06 23:44:563717 // Quit after hitting the redirect, so can check the headers.
3718 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193719 r->Start();
[email protected]255620da2013-08-19 13:14:293720 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123721
[email protected]6be6fa92014-08-06 23:44:563722 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193723 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3724 EXPECT_EQ(307, r->GetResponseCode());
3725 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563726 std::string location;
[email protected]f7022f32014-08-21 16:32:193727 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3728 &location));
[email protected]6be6fa92014-08-06 23:44:563729 EXPECT_EQ(redirect_url, GURL(location));
3730
3731 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193732 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563733 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193734 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553735 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273736 EXPECT_EQ(
3737 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553738 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3739 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273740
[email protected]f7022f32014-08-21 16:32:193741 EXPECT_EQ(0, r->status().error());
3742 EXPECT_EQ(redirect_url, r->url());
3743 EXPECT_EQ(original_url, r->original_url());
3744 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123745 EXPECT_EQ(1, network_delegate.created_requests());
3746 EXPECT_EQ(0, network_delegate.destroyed_requests());
3747 }
3748 EXPECT_EQ(1, network_delegate.destroyed_requests());
3749}
3750
[email protected]b813ed72012-04-05 08:21:363751// Tests that the network delegate can block and redirect a request to a new
3752// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3753TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:553754 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:363755
3756 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303757 BlockingNetworkDelegate network_delegate(
3758 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:553759 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:363760 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363761
[email protected]d5a4dd62012-05-23 01:41:043762 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553763 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363764
3765 {
tommycli59a63432015-11-06 00:10:553766 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363767 scoped_ptr<URLRequest> r(
3768 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363769
[email protected]6be6fa92014-08-06 23:44:563770 // Quit after hitting the redirect, so can check the headers.
3771 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193772 r->Start();
[email protected]255620da2013-08-19 13:14:293773 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363774
[email protected]6be6fa92014-08-06 23:44:563775 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193776 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3777 EXPECT_EQ(307, r->GetResponseCode());
3778 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563779 std::string location;
[email protected]f7022f32014-08-21 16:32:193780 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3781 &location));
[email protected]6be6fa92014-08-06 23:44:563782 EXPECT_EQ(redirect_url, GURL(location));
3783
3784 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193785 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563786 base::RunLoop().Run();
3787
[email protected]f7022f32014-08-21 16:32:193788 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553789 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273790 EXPECT_EQ(
3791 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553792 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3793 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193794 EXPECT_EQ(0, r->status().error());
3795 EXPECT_EQ(redirect_url, r->url());
3796 EXPECT_EQ(original_url, r->original_url());
3797 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363798 EXPECT_EQ(1, network_delegate.created_requests());
3799 EXPECT_EQ(0, network_delegate.destroyed_requests());
3800 }
3801 EXPECT_EQ(1, network_delegate.destroyed_requests());
3802}
3803
[email protected]3c5ca8c2011-09-29 01:14:513804// Tests that redirects caused by the network delegate preserve POST data.
3805TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:553806 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:513807
3808 const char kData[] = "hello world";
3809
3810 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303811 BlockingNetworkDelegate network_delegate(
3812 BlockingNetworkDelegate::AUTO_CALLBACK);
3813 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553814 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:513815 network_delegate.set_redirect_url(redirect_url);
3816
[email protected]ef2bf422012-05-11 03:27:093817 TestURLRequestContext context(true);
3818 context.set_network_delegate(&network_delegate);
3819 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513820
3821 {
tommycli59a63432015-11-06 00:10:553822 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363823 scoped_ptr<URLRequest> r(
3824 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193825 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073826 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513827 HttpRequestHeaders headers;
3828 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513829 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193830 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563831
3832 // Quit after hitting the redirect, so can check the headers.
3833 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193834 r->Start();
[email protected]255620da2013-08-19 13:14:293835 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513836
[email protected]6be6fa92014-08-06 23:44:563837 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193838 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3839 EXPECT_EQ(307, r->GetResponseCode());
3840 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563841 std::string location;
[email protected]f7022f32014-08-21 16:32:193842 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3843 &location));
[email protected]6be6fa92014-08-06 23:44:563844 EXPECT_EQ(redirect_url, GURL(location));
3845
3846 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193847 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563848 base::RunLoop().Run();
3849
[email protected]f7022f32014-08-21 16:32:193850 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3851 EXPECT_EQ(0, r->status().error());
3852 EXPECT_EQ(redirect_url, r->url());
3853 EXPECT_EQ(original_url, r->original_url());
3854 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513855 EXPECT_EQ(1, network_delegate.created_requests());
3856 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193857 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513858 EXPECT_EQ(kData, d.data_received());
3859 }
3860 EXPECT_EQ(1, network_delegate.destroyed_requests());
3861}
3862
[email protected]5f714132014-03-26 10:41:163863// Tests that the network delegate can block and redirect a request to a new
3864// URL during OnHeadersReceived.
3865TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:553866 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:163867
3868 TestDelegate d;
3869 BlockingNetworkDelegate network_delegate(
3870 BlockingNetworkDelegate::AUTO_CALLBACK);
3871 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:553872 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:163873 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3874
3875 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553876 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:163877
3878 {
tommycli59a63432015-11-06 00:10:553879 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:363880 scoped_ptr<URLRequest> r(
3881 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163882
[email protected]f7022f32014-08-21 16:32:193883 r->Start();
[email protected]5f714132014-03-26 10:41:163884 base::RunLoop().Run();
3885
[email protected]f7022f32014-08-21 16:32:193886 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553887 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273888 EXPECT_EQ(
3889 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
tommycli59a63432015-11-06 00:10:553890 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3891 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193892
3893 EXPECT_EQ(OK, r->status().error());
3894 EXPECT_EQ(redirect_url, r->url());
3895 EXPECT_EQ(original_url, r->original_url());
3896 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163897 EXPECT_EQ(2, network_delegate.created_requests());
3898 EXPECT_EQ(0, network_delegate.destroyed_requests());
3899 }
3900 EXPECT_EQ(1, network_delegate.destroyed_requests());
3901}
3902
[email protected]c2911d72011-10-03 22:16:363903// Tests that the network delegate can synchronously complete OnAuthRequired
3904// by taking no action. This indicates that the NetworkDelegate does not want to
3905// handle the challenge, and is passing the buck along to the
3906// URLRequest::Delegate.
3907TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:553908 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363909
3910 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303911 BlockingNetworkDelegate network_delegate(
3912 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363913
[email protected]ef2bf422012-05-11 03:27:093914 TestURLRequestContext context(true);
3915 context.set_network_delegate(&network_delegate);
3916 context.Init();
[email protected]c2911d72011-10-03 22:16:363917
[email protected]f3cf9802011-10-28 18:44:583918 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363919
3920 {
tommycli59a63432015-11-06 00:10:553921 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363922 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193923 r->Start();
[email protected]79e1fd62013-06-20 06:50:043924
[email protected]255620da2013-08-19 13:14:293925 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043926
[email protected]f7022f32014-08-21 16:32:193927 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3928 EXPECT_EQ(0, r->status().error());
3929 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043930 EXPECT_TRUE(d.auth_required_called());
3931 EXPECT_EQ(1, network_delegate.created_requests());
3932 EXPECT_EQ(0, network_delegate.destroyed_requests());
3933 }
3934 EXPECT_EQ(1, network_delegate.destroyed_requests());
3935}
3936
3937TEST_F(URLRequestTestHTTP,
3938 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:553939 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:043940
3941 TestDelegate d;
3942 BlockingNetworkDelegate network_delegate(
3943 BlockingNetworkDelegate::SYNCHRONOUS);
3944
3945 TestURLRequestContext context(true);
3946 context.set_network_delegate(&network_delegate);
3947 context.Init();
3948
3949 d.set_credentials(AuthCredentials(kUser, kSecret));
3950
3951 {
tommycli59a63432015-11-06 00:10:553952 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363953 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193954 r->Start();
[email protected]79e1fd62013-06-20 06:50:043955
3956 {
3957 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193958 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043959 EXPECT_FALSE(headers.HasHeader("Authorization"));
3960 }
3961
[email protected]255620da2013-08-19 13:14:293962 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363963
[email protected]f7022f32014-08-21 16:32:193964 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3965 EXPECT_EQ(0, r->status().error());
3966 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363967 EXPECT_TRUE(d.auth_required_called());
3968 EXPECT_EQ(1, network_delegate.created_requests());
3969 EXPECT_EQ(0, network_delegate.destroyed_requests());
3970 }
3971 EXPECT_EQ(1, network_delegate.destroyed_requests());
3972}
3973
3974// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403975// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363976TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:553977 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363978
3979 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303980 BlockingNetworkDelegate network_delegate(
3981 BlockingNetworkDelegate::SYNCHRONOUS);
3982 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363983 network_delegate.set_auth_retval(
3984 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3985
[email protected]f3cf9802011-10-28 18:44:583986 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363987
[email protected]ef2bf422012-05-11 03:27:093988 TestURLRequestContext context(true);
3989 context.set_network_delegate(&network_delegate);
3990 context.Init();
[email protected]c2911d72011-10-03 22:16:363991
3992 {
tommycli59a63432015-11-06 00:10:553993 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:363994 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193995 r->Start();
[email protected]255620da2013-08-19 13:14:293996 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363997
[email protected]f7022f32014-08-21 16:32:193998 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3999 EXPECT_EQ(0, r->status().error());
4000 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364001 EXPECT_FALSE(d.auth_required_called());
4002 EXPECT_EQ(1, network_delegate.created_requests());
4003 EXPECT_EQ(0, network_delegate.destroyed_requests());
4004 }
4005 EXPECT_EQ(1, network_delegate.destroyed_requests());
4006}
4007
[email protected]79e1fd62013-06-20 06:50:044008// Same as above, but also tests that GetFullRequestHeaders returns the proper
4009// headers (for the first or second request) when called at the proper times.
4010TEST_F(URLRequestTestHTTP,
4011 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554012 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044013
4014 TestDelegate d;
4015 BlockingNetworkDelegate network_delegate(
4016 BlockingNetworkDelegate::SYNCHRONOUS);
4017 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4018 network_delegate.set_auth_retval(
4019 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4020
4021 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4022
4023 TestURLRequestContext context(true);
4024 context.set_network_delegate(&network_delegate);
4025 context.Init();
4026
4027 {
tommycli59a63432015-11-06 00:10:554028 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364029 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194030 r->Start();
[email protected]255620da2013-08-19 13:14:294031 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044032
[email protected]f7022f32014-08-21 16:32:194033 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4034 EXPECT_EQ(0, r->status().error());
4035 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044036 EXPECT_FALSE(d.auth_required_called());
4037 EXPECT_EQ(1, network_delegate.created_requests());
4038 EXPECT_EQ(0, network_delegate.destroyed_requests());
4039
4040 {
4041 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194042 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044043 EXPECT_TRUE(headers.HasHeader("Authorization"));
4044 }
4045 }
4046 EXPECT_EQ(1, network_delegate.destroyed_requests());
4047}
4048
[email protected]c2911d72011-10-03 22:16:364049// Tests that the network delegate can synchronously complete OnAuthRequired
4050// by cancelling authentication.
4051TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554052 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364053
4054 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304055 BlockingNetworkDelegate network_delegate(
4056 BlockingNetworkDelegate::SYNCHRONOUS);
4057 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364058 network_delegate.set_auth_retval(
4059 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4060
[email protected]ef2bf422012-05-11 03:27:094061 TestURLRequestContext context(true);
4062 context.set_network_delegate(&network_delegate);
4063 context.Init();
[email protected]c2911d72011-10-03 22:16:364064
4065 {
tommycli59a63432015-11-06 00:10:554066 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364067 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194068 r->Start();
[email protected]255620da2013-08-19 13:14:294069 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364070
[email protected]f7022f32014-08-21 16:32:194071 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4072 EXPECT_EQ(OK, r->status().error());
4073 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364074 EXPECT_FALSE(d.auth_required_called());
4075 EXPECT_EQ(1, network_delegate.created_requests());
4076 EXPECT_EQ(0, network_delegate.destroyed_requests());
4077 }
4078 EXPECT_EQ(1, network_delegate.destroyed_requests());
4079}
4080
4081// Tests that the network delegate can asynchronously complete OnAuthRequired
4082// by taking no action. This indicates that the NetworkDelegate does not want
4083// to handle the challenge, and is passing the buck along to the
4084// URLRequest::Delegate.
4085TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554086 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364087
4088 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304089 BlockingNetworkDelegate network_delegate(
4090 BlockingNetworkDelegate::AUTO_CALLBACK);
4091 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364092
[email protected]ef2bf422012-05-11 03:27:094093 TestURLRequestContext context(true);
4094 context.set_network_delegate(&network_delegate);
4095 context.Init();
[email protected]c2911d72011-10-03 22:16:364096
[email protected]f3cf9802011-10-28 18:44:584097 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364098
4099 {
tommycli59a63432015-11-06 00:10:554100 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364101 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194102 r->Start();
[email protected]255620da2013-08-19 13:14:294103 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364104
[email protected]f7022f32014-08-21 16:32:194105 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4106 EXPECT_EQ(0, r->status().error());
4107 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364108 EXPECT_TRUE(d.auth_required_called());
4109 EXPECT_EQ(1, network_delegate.created_requests());
4110 EXPECT_EQ(0, network_delegate.destroyed_requests());
4111 }
4112 EXPECT_EQ(1, network_delegate.destroyed_requests());
4113}
4114
4115// Tests that the network delegate can asynchronously complete OnAuthRequired
4116// by setting credentials.
4117TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554118 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364119
4120 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304121 BlockingNetworkDelegate network_delegate(
4122 BlockingNetworkDelegate::AUTO_CALLBACK);
4123 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364124 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364125 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4126
[email protected]f3cf9802011-10-28 18:44:584127 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364128 network_delegate.set_auth_credentials(auth_credentials);
4129
[email protected]ef2bf422012-05-11 03:27:094130 TestURLRequestContext context(true);
4131 context.set_network_delegate(&network_delegate);
4132 context.Init();
[email protected]c2911d72011-10-03 22:16:364133
4134 {
tommycli59a63432015-11-06 00:10:554135 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364136 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194137 r->Start();
[email protected]255620da2013-08-19 13:14:294138 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364139
[email protected]f7022f32014-08-21 16:32:194140 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4141 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:364142
[email protected]f7022f32014-08-21 16:32:194143 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364144 EXPECT_FALSE(d.auth_required_called());
4145 EXPECT_EQ(1, network_delegate.created_requests());
4146 EXPECT_EQ(0, network_delegate.destroyed_requests());
4147 }
4148 EXPECT_EQ(1, network_delegate.destroyed_requests());
4149}
4150
4151// Tests that the network delegate can asynchronously complete OnAuthRequired
4152// by cancelling authentication.
4153TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554154 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364155
4156 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304157 BlockingNetworkDelegate network_delegate(
4158 BlockingNetworkDelegate::AUTO_CALLBACK);
4159 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364160 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364161 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4162
[email protected]ef2bf422012-05-11 03:27:094163 TestURLRequestContext context(true);
4164 context.set_network_delegate(&network_delegate);
4165 context.Init();
[email protected]c2911d72011-10-03 22:16:364166
4167 {
tommycli59a63432015-11-06 00:10:554168 GURL url(http_test_server()->GetURL("/auth-basic"));
davidben151423e2015-03-23 18:48:364169 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194170 r->Start();
[email protected]255620da2013-08-19 13:14:294171 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364172
[email protected]f7022f32014-08-21 16:32:194173 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4174 EXPECT_EQ(OK, r->status().error());
4175 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364176 EXPECT_FALSE(d.auth_required_called());
4177 EXPECT_EQ(1, network_delegate.created_requests());
4178 EXPECT_EQ(0, network_delegate.destroyed_requests());
4179 }
4180 EXPECT_EQ(1, network_delegate.destroyed_requests());
4181}
4182
[email protected]9045b8822012-01-13 20:35:354183// Tests that we can handle when a network request was canceled while we were
4184// waiting for the network delegate.
4185// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4186TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554187 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354188
4189 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304190 BlockingNetworkDelegate network_delegate(
4191 BlockingNetworkDelegate::USER_CALLBACK);
4192 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354193
[email protected]ef2bf422012-05-11 03:27:094194 TestURLRequestContext context(true);
4195 context.set_network_delegate(&network_delegate);
4196 context.Init();
[email protected]9045b8822012-01-13 20:35:354197
4198 {
[email protected]f7022f32014-08-21 16:32:194199 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554200 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354201
[email protected]f7022f32014-08-21 16:32:194202 r->Start();
[email protected]255620da2013-08-19 13:14:294203 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304204 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4205 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354206 EXPECT_EQ(0, network_delegate.completed_requests());
4207 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194208 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354209 // Ensure that network delegate is notified.
4210 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194211 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4212 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354213 EXPECT_EQ(1, network_delegate.created_requests());
4214 EXPECT_EQ(0, network_delegate.destroyed_requests());
4215 }
4216 EXPECT_EQ(1, network_delegate.destroyed_requests());
4217}
4218
4219// Tests that we can handle when a network request was canceled while we were
4220// waiting for the network delegate.
4221// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
4222TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554223 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354224
4225 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304226 BlockingNetworkDelegate network_delegate(
4227 BlockingNetworkDelegate::USER_CALLBACK);
4228 network_delegate.set_block_on(
4229 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354230
[email protected]ef2bf422012-05-11 03:27:094231 TestURLRequestContext context(true);
4232 context.set_network_delegate(&network_delegate);
4233 context.Init();
[email protected]9045b8822012-01-13 20:35:354234
4235 {
[email protected]f7022f32014-08-21 16:32:194236 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554237 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354238
[email protected]f7022f32014-08-21 16:32:194239 r->Start();
[email protected]255620da2013-08-19 13:14:294240 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304241 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4242 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354243 EXPECT_EQ(0, network_delegate.completed_requests());
4244 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194245 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354246 // Ensure that network delegate is notified.
4247 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194248 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4249 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354250 EXPECT_EQ(1, network_delegate.created_requests());
4251 EXPECT_EQ(0, network_delegate.destroyed_requests());
4252 }
4253 EXPECT_EQ(1, network_delegate.destroyed_requests());
4254}
4255
4256// Tests that we can handle when a network request was canceled while we were
4257// waiting for the network delegate.
4258// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4259TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554260 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354261
4262 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304263 BlockingNetworkDelegate network_delegate(
4264 BlockingNetworkDelegate::USER_CALLBACK);
4265 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354266
[email protected]ef2bf422012-05-11 03:27:094267 TestURLRequestContext context(true);
4268 context.set_network_delegate(&network_delegate);
4269 context.Init();
[email protected]9045b8822012-01-13 20:35:354270
4271 {
[email protected]f7022f32014-08-21 16:32:194272 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554273 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354274
[email protected]f7022f32014-08-21 16:32:194275 r->Start();
[email protected]255620da2013-08-19 13:14:294276 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304277 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4278 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354279 EXPECT_EQ(0, network_delegate.completed_requests());
4280 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194281 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354282 // Ensure that network delegate is notified.
4283 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194284 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4285 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354286 EXPECT_EQ(1, network_delegate.created_requests());
4287 EXPECT_EQ(0, network_delegate.destroyed_requests());
4288 }
4289 EXPECT_EQ(1, network_delegate.destroyed_requests());
4290}
4291
4292// Tests that we can handle when a network request was canceled while we were
4293// waiting for the network delegate.
4294// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024295TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554296 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354297
4298 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304299 BlockingNetworkDelegate network_delegate(
4300 BlockingNetworkDelegate::USER_CALLBACK);
4301 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354302
[email protected]ef2bf422012-05-11 03:27:094303 TestURLRequestContext context(true);
4304 context.set_network_delegate(&network_delegate);
4305 context.Init();
[email protected]9045b8822012-01-13 20:35:354306
4307 {
[email protected]f7022f32014-08-21 16:32:194308 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554309 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354310
[email protected]f7022f32014-08-21 16:32:194311 r->Start();
[email protected]255620da2013-08-19 13:14:294312 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304313 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4314 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354315 EXPECT_EQ(0, network_delegate.completed_requests());
4316 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194317 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354318 // Ensure that network delegate is notified.
4319 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194320 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4321 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354322 EXPECT_EQ(1, network_delegate.created_requests());
4323 EXPECT_EQ(0, network_delegate.destroyed_requests());
4324 }
4325 EXPECT_EQ(1, network_delegate.destroyed_requests());
4326}
4327
tommycli59a63432015-11-06 00:10:554328namespace {
4329
4330scoped_ptr<test_server::HttpResponse> HandleServerAuthConnect(
4331 const test_server::HttpRequest& request) {
4332 if (request.headers.find("Host") == request.headers.end() ||
4333 request.headers.at("Host") != "www.server-auth.com" ||
4334 request.method != test_server::METHOD_CONNECT) {
4335 return nullptr;
4336 }
4337
4338 scoped_ptr<test_server::BasicHttpResponse> http_response(
4339 new test_server::BasicHttpResponse);
4340 http_response->set_code(HTTP_UNAUTHORIZED);
4341 http_response->AddCustomHeader("WWW-Authenticate",
4342 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:484343 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554344}
4345
4346} // namespace
4347
4348// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114349// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554350// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354351TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554352 http_test_server()->RegisterRequestHandler(
4353 base::Bind(&HandleServerAuthConnect));
4354 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114355
[email protected]ceefd7fd2012-11-29 00:36:244356 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044357 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554358 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504359
[email protected]dc651782009-02-14 01:45:084360 TestDelegate d;
4361 {
[email protected]f7022f32014-08-21 16:32:194362 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364363 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084364
[email protected]f7022f32014-08-21 16:32:194365 r->Start();
4366 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084367
[email protected]255620da2013-08-19 13:14:294368 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084369
[email protected]f7022f32014-08-21 16:32:194370 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:154371 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:194372 EXPECT_TRUE(r->proxy_server().IsEmpty());
4373 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:084374 }
4375}
4376
[email protected]b89290212009-08-14 22:37:354377TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554378 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114379
initial.commit586acc5fe2008-07-26 22:42:524380 TestDelegate d;
4381 {
[email protected]f7022f32014-08-21 16:32:194382 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554383 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524384
[email protected]f7022f32014-08-21 16:32:194385 r->Start();
4386 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524387
[email protected]255620da2013-08-19 13:14:294388 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524389
4390 EXPECT_EQ(1, d.response_started_count());
4391 EXPECT_FALSE(d.received_data_before_response());
4392 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554393 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194394 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554395 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194396 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164397
[email protected]9e743cd2010-03-16 07:03:534398 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524399 }
initial.commit586acc5fe2008-07-26 22:42:524400}
4401
[email protected]263163f2012-06-14 22:40:344402// This test has the server send a large number of cookies to the client.
4403// To ensure that no number of cookies causes a crash, a galloping binary
4404// search is used to estimate that maximum number of cookies that are accepted
4405// by the browser. Beyond the maximum number, the request will fail with
4406// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304407#if defined(OS_WIN)
4408// http://crbug.com/177916
4409#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4410#else
4411#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4412#endif // defined(OS_WIN)
4413TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554414 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344415
4416 int lower_bound = 0;
4417 int upper_bound = 1;
4418
4419 // Double the number of cookies until the response header limits are
4420 // exceeded.
4421 while (DoManyCookiesRequest(upper_bound)) {
4422 lower_bound = upper_bound;
4423 upper_bound *= 2;
4424 ASSERT_LT(upper_bound, 1000000);
4425 }
4426
pkasting6b68a162014-12-01 22:10:294427 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344428 if (tolerance < 2)
4429 tolerance = 2;
4430
4431 // Perform a binary search to find the highest possible number of cookies,
4432 // within the desired tolerance.
4433 while (upper_bound - lower_bound >= tolerance) {
4434 int num_cookies = (lower_bound + upper_bound) / 2;
4435
4436 if (DoManyCookiesRequest(num_cookies))
4437 lower_bound = num_cookies;
4438 else
4439 upper_bound = num_cookies;
4440 }
4441 // Success: the test did not crash.
4442}
4443
[email protected]b89290212009-08-14 22:37:354444TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554445 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114446
initial.commit586acc5fe2008-07-26 22:42:524447 TestDelegate d;
4448 {
[email protected]f7022f32014-08-21 16:32:194449 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554450 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524451
[email protected]f7022f32014-08-21 16:32:194452 r->Start();
4453 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524454
[email protected]255620da2013-08-19 13:14:294455 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524456
4457 EXPECT_EQ(1, d.response_started_count());
4458 EXPECT_FALSE(d.received_data_before_response());
4459 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554460 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194461 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554462 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194463 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524464 }
[email protected]5d7b373e2009-09-02 07:19:034465}
4466
[email protected]79e1fd62013-06-20 06:50:044467TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554468 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044469
4470 TestDelegate d;
4471 {
tommycli59a63432015-11-06 00:10:554472 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
davidben151423e2015-03-23 18:48:364473 scoped_ptr<URLRequest> r(
4474 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044475
4476 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194477 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044478
[email protected]f7022f32014-08-21 16:32:194479 r->Start();
4480 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044481
[email protected]255620da2013-08-19 13:14:294482 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044483
4484 EXPECT_EQ(1, d.response_started_count());
4485 EXPECT_FALSE(d.received_data_before_response());
4486 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554487 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194488 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554489 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194490 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044491
4492 EXPECT_TRUE(d.have_full_request_headers());
4493 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4494 }
4495}
4496
[email protected]58e32bb2013-01-21 18:23:254497TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554498 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254499
4500 TestDelegate d;
4501 {
[email protected]f7022f32014-08-21 16:32:194502 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554503 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254504
[email protected]f7022f32014-08-21 16:32:194505 r->Start();
4506 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254507
[email protected]255620da2013-08-19 13:14:294508 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254509
4510 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194511 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254512 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4513
4514 EXPECT_EQ(1, d.response_started_count());
4515 EXPECT_FALSE(d.received_data_before_response());
4516 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554517 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194518 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554519 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194520 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254521 }
4522}
4523
tommycli59a63432015-11-06 00:10:554524// TODO(svaldez): Update tests to use EmbeddedTestServer.
4525#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394526TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:554527 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
4528 SpawnedTestServer::kLocalhost,
4529 base::FilePath(kTestFilePath));
4530
4531 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:394532
4533 // Parameter that specifies the Content-Length field in the response:
4534 // C - Compressed length.
4535 // U - Uncompressed length.
4536 // L - Large length (larger than both C & U).
4537 // M - Medium length (between C & U).
4538 // S - Small length (smaller than both C & U).
4539 const char test_parameters[] = "CULMS";
4540 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4541 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444542 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394543 // S has too little data, but we seem to accept it.
4544 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374545 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394546
4547 for (int i = 0; i < num_tests ; i++) {
4548 TestDelegate d;
4549 {
tommycli59a63432015-11-06 00:10:554550 std::string test_file = base::StringPrintf(
4551 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394552
[email protected]ceefd7fd2012-11-29 00:36:244553 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094554 TestURLRequestContext context(true);
4555 context.set_network_delegate(&network_delegate);
4556 context.Init();
[email protected]87a09a92011-07-14 15:50:504557
[email protected]f7022f32014-08-21 16:32:194558 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554559 test_server.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194560 r->Start();
4561 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394562
[email protected]255620da2013-08-19 13:14:294563 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394564
4565 EXPECT_EQ(1, d.response_started_count());
4566 EXPECT_FALSE(d.received_data_before_response());
4567 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194568 << " status = " << r->status().status()
4569 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394570 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194571 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394572 << " Parameter = \"" << test_file << "\"";
4573 } else {
[email protected]f7022f32014-08-21 16:32:194574 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4575 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394576 << " Parameter = \"" << test_file << "\"";
4577 }
4578 }
4579 }
4580}
tommycli59a63432015-11-06 00:10:554581#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394582
tbansala1caf9612015-06-01 20:24:184583TEST_F(URLRequestTestHTTP, NetworkQualityEstimator) {
tommycli59a63432015-11-06 00:10:554584 ASSERT_TRUE(http_test_server()->Start());
tbansalea2fb8c2015-05-22 22:23:004585 // Enable requests to local host to be used for network quality estimation.
tbansalb177b5392015-06-25 11:13:024586 std::map<std::string, std::string> variation_params;
tbansal1c92d5b2015-08-14 20:14:434587 NetworkQualityEstimator estimator(scoped_ptr<net::ExternalEstimateProvider>(),
4588 variation_params, true, true);
tbansalea2fb8c2015-05-22 22:23:004589
4590 TestDelegate d;
4591 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4592 TestURLRequestContext context(true);
4593 context.set_network_quality_estimator(&estimator);
4594 context.set_network_delegate(&network_delegate);
4595 context.Init();
4596
tommycli59a63432015-11-06 00:10:554597 std::string url = "/defaultresponse";
tbansalea2fb8c2015-05-22 22:23:004598
tommycli59a63432015-11-06 00:10:554599 scoped_ptr<URLRequest> r(context.CreateRequest(
4600 http_test_server()->GetURL(url), DEFAULT_PRIORITY, &d));
tbansalea2fb8c2015-05-22 22:23:004601 r->Start();
4602
4603 base::RunLoop().Run();
4604
tbansal9533b6f2015-08-11 22:06:084605 base::TimeDelta rtt;
4606 int32_t kbps;
4607 EXPECT_TRUE(estimator.GetRTTEstimate(&rtt));
4608 EXPECT_TRUE(estimator.GetDownlinkThroughputKbpsEstimate(&kbps));
4609 EXPECT_GE(rtt, base::TimeDelta());
4610 EXPECT_LT(rtt, base::TimeDelta::Max());
4611 EXPECT_GT(kbps, 0);
tbansalea2fb8c2015-05-22 22:23:004612
4613 // Verify that histograms are not populated. They should populate only when
4614 // there is a change in ConnectionType.
4615 base::HistogramTester histogram_tester;
4616 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 0);
4617 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 0);
4618
4619 NetworkChangeNotifier::NotifyObserversOfConnectionTypeChangeForTests(
4620 NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI);
4621 base::MessageLoop::current()->RunUntilIdle();
4622 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 1);
4623 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 1);
4624}
4625
[email protected]58e32bb2013-01-21 18:23:254626TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:554627 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254628
tommycli59a63432015-11-06 00:10:554629 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454630 GURL original_url =
tommycli59a63432015-11-06 00:10:554631 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254632 TestDelegate d;
davidben151423e2015-03-23 18:48:364633 scoped_ptr<URLRequest> req(
4634 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194635 req->Start();
[email protected]255620da2013-08-19 13:14:294636 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254637
4638 EXPECT_EQ(1, d.response_started_count());
4639 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194640 EXPECT_EQ(destination_url, req->url());
4641 EXPECT_EQ(original_url, req->original_url());
4642 ASSERT_EQ(2U, req->url_chain().size());
4643 EXPECT_EQ(original_url, req->url_chain()[0]);
4644 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254645
4646 LoadTimingInfo load_timing_info_before_redirect;
4647 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4648 &load_timing_info_before_redirect));
4649 TestLoadTimingNotReused(load_timing_info_before_redirect,
4650 CONNECT_TIMING_HAS_DNS_TIMES);
4651
4652 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194653 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254654 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4655
4656 // Check that a new socket was used on redirect, since the server does not
4657 // supposed keep-alive sockets, and that the times before the redirect are
4658 // before the ones recorded for the second request.
4659 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4660 load_timing_info.socket_log_id);
4661 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4662 load_timing_info.connect_timing.connect_start);
4663}
4664
[email protected]8f1ac082011-04-19 21:14:134665TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:554666 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:134667
tommycli59a63432015-11-06 00:10:554668 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454669 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:554670 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
4671 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
4672 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:134673 TestDelegate d;
davidben151423e2015-03-23 18:48:364674 scoped_ptr<URLRequest> req(
4675 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194676 req->Start();
[email protected]255620da2013-08-19 13:14:294677 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134678
4679 EXPECT_EQ(1, d.response_started_count());
4680 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194681 EXPECT_EQ(destination_url, req->url());
4682 EXPECT_EQ(original_url, req->original_url());
4683 ASSERT_EQ(3U, req->url_chain().size());
4684 EXPECT_EQ(original_url, req->url_chain()[0]);
4685 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4686 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134687}
4688
[email protected]abe1c4a2013-10-25 19:28:514689// First and second pieces of information logged by delegates to URLRequests.
4690const char kFirstDelegateInfo[] = "Wonderful delegate";
4691const char kSecondDelegateInfo[] = "Exciting delegate";
4692
4693// Logs delegate information to a URLRequest. The first string is logged
4694// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4695// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4696// another asynchronous call is used to clear the delegate information
4697// before calling a callback. The object then deletes itself.
4698class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4699 public:
4700 typedef base::Callback<void()> Callback;
4701
4702 // Each time delegate information is added to the URLRequest, the resulting
4703 // load state is checked. The expected load state after each request is
4704 // passed in as an argument.
4705 static void Run(URLRequest* url_request,
4706 LoadState expected_first_load_state,
4707 LoadState expected_second_load_state,
4708 LoadState expected_third_load_state,
4709 const Callback& callback) {
4710 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4711 url_request,
4712 expected_first_load_state,
4713 expected_second_load_state,
4714 expected_third_load_state,
4715 callback);
4716 logger->Start();
4717 }
4718
4719 // Checks that the log entries, starting with log_position, contain the
4720 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4721 // recorded. Returns the index of entry after the expected number of
4722 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464723 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514724 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514725 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4726 if (log_position + 3 >= entries.size()) {
4727 ADD_FAILURE() << "Not enough log entries";
4728 return entries.size();
4729 }
4730 std::string delegate_info;
4731 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4732 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4733 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4734 &delegate_info));
4735 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4736
4737 ++log_position;
4738 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4739 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4740
4741 ++log_position;
4742 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4743 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4744 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4745 &delegate_info));
4746 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4747
4748 ++log_position;
4749 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4750 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4751
4752 return log_position + 1;
4753 }
4754
[email protected]1826a402014-01-08 15:40:484755 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4756 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464757 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4758 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484759 log_position =
4760 ExpectLogContainsSomewhereAfter(entries,
4761 log_position,
4762 NetLog::TYPE_URL_REQUEST_DELEGATE,
4763 NetLog::PHASE_BEGIN);
4764 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4765 entries[log_position + 1].type);
4766 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4767 return log_position + 1;
4768 }
4769
[email protected]abe1c4a2013-10-25 19:28:514770 private:
4771 friend class base::RefCounted<AsyncDelegateLogger>;
4772
4773 AsyncDelegateLogger(URLRequest* url_request,
4774 LoadState expected_first_load_state,
4775 LoadState expected_second_load_state,
4776 LoadState expected_third_load_state,
4777 const Callback& callback)
4778 : url_request_(url_request),
4779 expected_first_load_state_(expected_first_load_state),
4780 expected_second_load_state_(expected_second_load_state),
4781 expected_third_load_state_(expected_third_load_state),
4782 callback_(callback) {
4783 }
4784
4785 ~AsyncDelegateLogger() {}
4786
4787 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534788 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514789 LoadStateWithParam load_state = url_request_->GetLoadState();
4790 EXPECT_EQ(expected_first_load_state_, load_state.state);
4791 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454792 base::ThreadTaskRunnerHandle::Get()->PostTask(
4793 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514794 }
4795
4796 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534797 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514798 LoadStateWithParam load_state = url_request_->GetLoadState();
4799 EXPECT_EQ(expected_second_load_state_, load_state.state);
4800 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4801 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4802 } else {
4803 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4804 }
skyostil4891b25b2015-06-11 11:43:454805 base::ThreadTaskRunnerHandle::Get()->PostTask(
4806 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514807 }
4808
4809 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534810 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514811 LoadStateWithParam load_state = url_request_->GetLoadState();
4812 EXPECT_EQ(expected_third_load_state_, load_state.state);
4813 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084814 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514815 callback_.Run();
4816 }
4817
4818 URLRequest* url_request_;
4819 const int expected_first_load_state_;
4820 const int expected_second_load_state_;
4821 const int expected_third_load_state_;
4822 const Callback callback_;
4823
4824 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4825};
4826
4827// NetworkDelegate that logs delegate information before a request is started,
4828// before headers are sent, when headers are read, and when auth information
4829// is requested. Uses AsyncDelegateLogger.
4830class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4831 public:
4832 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204833 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514834
4835 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204836 int OnBeforeURLRequest(URLRequest* request,
4837 const CompletionCallback& callback,
4838 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514839 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4840 return RunCallbackAsynchronously(request, callback);
4841 }
4842
dchengb03027d2014-10-21 12:00:204843 int OnBeforeSendHeaders(URLRequest* request,
4844 const CompletionCallback& callback,
4845 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514846 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4847 return RunCallbackAsynchronously(request, callback);
4848 }
4849
dchengb03027d2014-10-21 12:00:204850 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514851 URLRequest* request,
4852 const CompletionCallback& callback,
4853 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164854 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134855 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164856 TestNetworkDelegate::OnHeadersReceived(request,
4857 callback,
[email protected]abe1c4a2013-10-25 19:28:514858 original_response_headers,
[email protected]5f714132014-03-26 10:41:164859 override_response_headers,
4860 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514861 return RunCallbackAsynchronously(request, callback);
4862 }
4863
dchengb03027d2014-10-21 12:00:204864 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514865 URLRequest* request,
4866 const AuthChallengeInfo& auth_info,
4867 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134868 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514869 AsyncDelegateLogger::Run(
4870 request,
4871 LOAD_STATE_WAITING_FOR_DELEGATE,
4872 LOAD_STATE_WAITING_FOR_DELEGATE,
4873 LOAD_STATE_WAITING_FOR_DELEGATE,
4874 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4875 callback, credentials));
4876 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4877 }
4878
4879 private:
4880 static int RunCallbackAsynchronously(
4881 URLRequest* request,
4882 const CompletionCallback& callback) {
4883 AsyncDelegateLogger::Run(
4884 request,
4885 LOAD_STATE_WAITING_FOR_DELEGATE,
4886 LOAD_STATE_WAITING_FOR_DELEGATE,
4887 LOAD_STATE_WAITING_FOR_DELEGATE,
4888 base::Bind(callback, OK));
4889 return ERR_IO_PENDING;
4890 }
4891
4892 static void SetAuthAndResume(const AuthCallback& callback,
4893 AuthCredentials* credentials) {
4894 *credentials = AuthCredentials(kUser, kSecret);
4895 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4896 }
4897
4898 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4899};
4900
4901// URLRequest::Delegate that logs delegate information when the headers
4902// are received, when each read completes, and during redirects. Uses
4903// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4904//
4905// Inherits from TestDelegate to reuse the TestDelegate code to handle
4906// advancing to the next step in most cases, as well as cancellation.
4907class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4908 public:
4909 enum CancelStage {
4910 NO_CANCEL = 0,
4911 CANCEL_ON_RECEIVED_REDIRECT,
4912 CANCEL_ON_RESPONSE_STARTED,
4913 CANCEL_ON_READ_COMPLETED
4914 };
4915
4916 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4917 : cancel_stage_(cancel_stage) {
4918 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4919 set_cancel_in_received_redirect(true);
4920 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4921 set_cancel_in_response_started(true);
4922 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4923 set_cancel_in_received_data(true);
4924 }
dchengb03027d2014-10-21 12:00:204925 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514926
4927 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204928 void OnReceivedRedirect(URLRequest* request,
4929 const RedirectInfo& redirect_info,
4930 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514931 *defer_redirect = true;
4932 AsyncDelegateLogger::Run(
4933 request,
4934 LOAD_STATE_WAITING_FOR_DELEGATE,
4935 LOAD_STATE_WAITING_FOR_DELEGATE,
4936 LOAD_STATE_WAITING_FOR_DELEGATE,
4937 base::Bind(
4938 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594939 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514940 }
4941
dchengb03027d2014-10-21 12:00:204942 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514943 AsyncDelegateLogger::Run(
4944 request,
4945 LOAD_STATE_WAITING_FOR_DELEGATE,
4946 LOAD_STATE_WAITING_FOR_DELEGATE,
4947 LOAD_STATE_WAITING_FOR_DELEGATE,
4948 base::Bind(
4949 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4950 base::Unretained(this), request));
4951 }
4952
dchengb03027d2014-10-21 12:00:204953 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514954 AsyncDelegateLogger::Run(
4955 request,
4956 LOAD_STATE_IDLE,
4957 LOAD_STATE_IDLE,
4958 LOAD_STATE_IDLE,
4959 base::Bind(
4960 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4961 base::Unretained(this), request, bytes_read));
4962 }
4963
4964 private:
4965 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594966 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514967 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594968 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514969 // FollowDeferredRedirect should not be called after cancellation.
4970 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4971 return;
4972 if (!defer_redirect)
4973 request->FollowDeferredRedirect();
4974 }
4975
4976 void OnResponseStartedLoggingComplete(URLRequest* request) {
4977 // The parent class continues the request.
4978 TestDelegate::OnResponseStarted(request);
4979 }
4980
4981 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4982 // The parent class continues the request.
4983 TestDelegate::OnReadCompleted(request, bytes_read);
4984 }
4985
4986 const CancelStage cancel_stage_;
4987
4988 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4989};
4990
4991// Tests handling of delegate info before a request starts.
4992TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:554993 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:514994
4995 TestDelegate request_delegate;
4996 TestURLRequestContext context(true);
4997 context.set_network_delegate(NULL);
4998 context.set_net_log(&net_log_);
4999 context.Init();
5000
5001 {
davidben151423e2015-03-23 18:48:365002 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555003 context.CreateRequest(http_test_server()->GetURL("/defaultresponse"),
davidben151423e2015-03-23 18:48:365004 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195005 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515006 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085007 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515008
5009 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195010 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515011 LOAD_STATE_WAITING_FOR_DELEGATE,
5012 LOAD_STATE_WAITING_FOR_DELEGATE,
5013 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195014 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515015
5016 base::RunLoop().Run();
5017
[email protected]f7022f32014-08-21 16:32:195018 EXPECT_EQ(200, r->GetResponseCode());
5019 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515020 }
5021
mmenke43758e62015-05-04 21:09:465022 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515023 net_log_.GetEntries(&entries);
5024 size_t log_position = ExpectLogContainsSomewhereAfter(
5025 entries,
5026 0,
5027 NetLog::TYPE_DELEGATE_INFO,
5028 NetLog::PHASE_BEGIN);
5029
5030 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5031
5032 // Nothing else should add any delegate info to the request.
5033 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5034 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5035}
5036
5037// Tests handling of delegate info from a network delegate.
5038TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555039 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515040
5041 TestDelegate request_delegate;
5042 AsyncLoggingNetworkDelegate network_delegate;
5043 TestURLRequestContext context(true);
5044 context.set_network_delegate(&network_delegate);
5045 context.set_net_log(&net_log_);
5046 context.Init();
5047
5048 {
davidben151423e2015-03-23 18:48:365049 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555050 context.CreateRequest(http_test_server()->GetURL("/simple.html"),
davidben151423e2015-03-23 18:48:365051 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195052 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515053 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085054 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515055
[email protected]f7022f32014-08-21 16:32:195056 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515057 base::RunLoop().Run();
5058
[email protected]f7022f32014-08-21 16:32:195059 EXPECT_EQ(200, r->GetResponseCode());
5060 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515061 EXPECT_EQ(1, network_delegate.created_requests());
5062 EXPECT_EQ(0, network_delegate.destroyed_requests());
5063 }
5064 EXPECT_EQ(1, network_delegate.destroyed_requests());
5065
5066 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465067 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515068 net_log_.GetEntries(&entries);
5069 for (size_t i = 0; i < 3; ++i) {
5070 log_position = ExpectLogContainsSomewhereAfter(
5071 entries,
5072 log_position + 1,
5073 NetLog::TYPE_URL_REQUEST_DELEGATE,
5074 NetLog::PHASE_BEGIN);
5075
5076 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5077 log_position + 1);
5078
5079 ASSERT_LT(log_position, entries.size());
5080 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5081 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485082
5083 if (i == 1) {
5084 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5085 entries, log_position + 1);
5086 }
[email protected]abe1c4a2013-10-25 19:28:515087 }
5088
5089 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5090 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5091}
5092
5093// Tests handling of delegate info from a network delegate in the case of an
5094// HTTP redirect.
5095TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555096 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515097
5098 TestDelegate request_delegate;
5099 AsyncLoggingNetworkDelegate network_delegate;
5100 TestURLRequestContext context(true);
5101 context.set_network_delegate(&network_delegate);
5102 context.set_net_log(&net_log_);
5103 context.Init();
5104
5105 {
[email protected]f7022f32014-08-21 16:32:195106 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555107 http_test_server()->GetURL("/server-redirect?simple.html"),
5108 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195109 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515110 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085111 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515112
[email protected]f7022f32014-08-21 16:32:195113 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515114 base::RunLoop().Run();
5115
[email protected]f7022f32014-08-21 16:32:195116 EXPECT_EQ(200, r->GetResponseCode());
5117 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515118 EXPECT_EQ(2, network_delegate.created_requests());
5119 EXPECT_EQ(0, network_delegate.destroyed_requests());
5120 }
5121 EXPECT_EQ(1, network_delegate.destroyed_requests());
5122
5123 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465124 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515125 net_log_.GetEntries(&entries);
5126 // The NetworkDelegate logged information in OnBeforeURLRequest,
5127 // OnBeforeSendHeaders, and OnHeadersReceived.
5128 for (size_t i = 0; i < 3; ++i) {
5129 log_position = ExpectLogContainsSomewhereAfter(
5130 entries,
5131 log_position + 1,
5132 NetLog::TYPE_URL_REQUEST_DELEGATE,
5133 NetLog::PHASE_BEGIN);
5134
5135 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5136 log_position + 1);
5137
5138 ASSERT_LT(log_position, entries.size());
5139 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5140 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485141
5142 if (i == 1) {
5143 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5144 entries, log_position + 1);
5145 }
[email protected]abe1c4a2013-10-25 19:28:515146 }
5147
5148 // The URLRequest::Delegate then gets informed about the redirect.
5149 log_position = ExpectLogContainsSomewhereAfter(
5150 entries,
5151 log_position + 1,
5152 NetLog::TYPE_URL_REQUEST_DELEGATE,
5153 NetLog::PHASE_BEGIN);
5154
5155 // The NetworkDelegate logged information in the same three events as before.
5156 for (size_t i = 0; i < 3; ++i) {
5157 log_position = ExpectLogContainsSomewhereAfter(
5158 entries,
5159 log_position + 1,
5160 NetLog::TYPE_URL_REQUEST_DELEGATE,
5161 NetLog::PHASE_BEGIN);
5162
5163 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5164 log_position + 1);
5165
5166 ASSERT_LT(log_position, entries.size());
5167 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5168 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5169 }
5170
5171 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5172 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5173}
5174
5175// Tests handling of delegate info from a network delegate in the case of HTTP
5176// AUTH.
5177TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555178 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515179
5180 TestDelegate request_delegate;
5181 AsyncLoggingNetworkDelegate network_delegate;
5182 TestURLRequestContext context(true);
5183 context.set_network_delegate(&network_delegate);
5184 context.set_net_log(&net_log_);
5185 context.Init();
5186
5187 {
davidben151423e2015-03-23 18:48:365188 scoped_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555189 context.CreateRequest(http_test_server()->GetURL("/auth-basic"),
davidben151423e2015-03-23 18:48:365190 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195191 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515192 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085193 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515194
[email protected]f7022f32014-08-21 16:32:195195 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515196 base::RunLoop().Run();
5197
[email protected]f7022f32014-08-21 16:32:195198 EXPECT_EQ(200, r->GetResponseCode());
5199 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515200 EXPECT_EQ(1, network_delegate.created_requests());
5201 EXPECT_EQ(0, network_delegate.destroyed_requests());
5202 }
5203 EXPECT_EQ(1, network_delegate.destroyed_requests());
5204
5205 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465206 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515207 net_log_.GetEntries(&entries);
5208 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
5209 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
5210 // OnBeforeURLRequest and OnBeforeSendHeaders.
5211 for (size_t i = 0; i < 6; ++i) {
5212 log_position = ExpectLogContainsSomewhereAfter(
5213 entries,
5214 log_position + 1,
5215 NetLog::TYPE_URL_REQUEST_DELEGATE,
5216 NetLog::PHASE_BEGIN);
5217
5218 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5219 log_position + 1);
5220
5221 ASSERT_LT(log_position, entries.size());
5222 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5223 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485224
5225 if (i == 1) {
5226 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5227 entries, log_position + 1);
5228 }
[email protected]abe1c4a2013-10-25 19:28:515229 }
5230
5231 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5232 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5233}
5234
tommycli59a63432015-11-06 00:10:555235// TODO(svaldez): Update tests to use EmbeddedTestServer.
5236#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515237// Tests handling of delegate info from a URLRequest::Delegate.
5238TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555239 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
5240 SpawnedTestServer::kLocalhost,
5241 base::FilePath(kTestFilePath));
5242
5243 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515244
5245 AsyncLoggingUrlRequestDelegate request_delegate(
5246 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5247 TestURLRequestContext context(true);
5248 context.set_network_delegate(NULL);
5249 context.set_net_log(&net_log_);
5250 context.Init();
5251
5252 {
5253 // A chunked response with delays between chunks is used to make sure that
5254 // attempts by the URLRequest delegate to log information while reading the
5255 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485256 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515257 // that it occurs.
[email protected]f7022f32014-08-21 16:32:195258 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555259 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365260 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195261 LoadStateWithParam load_state = r->GetLoadState();
5262 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515263 base::RunLoop().Run();
5264
[email protected]f7022f32014-08-21 16:32:195265 EXPECT_EQ(200, r->GetResponseCode());
5266 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515267 }
5268
mmenke43758e62015-05-04 21:09:465269 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515270 net_log_.GetEntries(&entries);
5271
[email protected]1826a402014-01-08 15:40:485272 size_t log_position = 0;
5273
5274 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5275 entries, log_position);
5276
[email protected]abe1c4a2013-10-25 19:28:515277 // The delegate info should only have been logged on header complete. Other
5278 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:485279 log_position =
5280 ExpectLogContainsSomewhereAfter(entries,
5281 log_position + 1,
5282 NetLog::TYPE_URL_REQUEST_DELEGATE,
5283 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515284
5285 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5286 log_position + 1);
5287
5288 ASSERT_LT(log_position, entries.size());
5289 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5290 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5291
5292 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5293 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5294 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5295 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5296}
tommycli59a63432015-11-06 00:10:555297#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515298
5299// Tests handling of delegate info from a URLRequest::Delegate in the case of
5300// an HTTP redirect.
5301TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555302 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515303
5304 AsyncLoggingUrlRequestDelegate request_delegate(
5305 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5306 TestURLRequestContext context(true);
5307 context.set_network_delegate(NULL);
5308 context.set_net_log(&net_log_);
5309 context.Init();
5310
5311 {
[email protected]f7022f32014-08-21 16:32:195312 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555313 http_test_server()->GetURL("/server-redirect?simple.html"),
5314 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195315 LoadStateWithParam load_state = r->GetLoadState();
5316 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515317 base::RunLoop().Run();
5318
[email protected]f7022f32014-08-21 16:32:195319 EXPECT_EQ(200, r->GetResponseCode());
5320 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515321 }
5322
mmenke43758e62015-05-04 21:09:465323 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515324 net_log_.GetEntries(&entries);
5325
5326 // Delegate info should only have been logged in OnReceivedRedirect and
5327 // OnResponseStarted.
5328 size_t log_position = 0;
5329 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485330 if (i == 0) {
5331 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5332 entries, log_position) + 1;
5333 }
5334
[email protected]abe1c4a2013-10-25 19:28:515335 log_position = ExpectLogContainsSomewhereAfter(
5336 entries,
5337 log_position,
5338 NetLog::TYPE_URL_REQUEST_DELEGATE,
5339 NetLog::PHASE_BEGIN);
5340
5341 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5342 log_position + 1);
5343
5344 ASSERT_LT(log_position, entries.size());
5345 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5346 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5347 }
5348
5349 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5350 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5351 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5352 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5353}
5354
5355// Tests handling of delegate info from a URLRequest::Delegate in the case of
5356// an HTTP redirect, with cancellation at various points.
5357TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555358 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515359
5360 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5361 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5362 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5363 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5364 };
5365
5366 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5367 ++test_case) {
5368 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5369 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:515370 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:515371 context.set_network_delegate(NULL);
5372 context.set_net_log(&net_log);
5373 context.Init();
5374
5375 {
[email protected]f7022f32014-08-21 16:32:195376 scoped_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555377 http_test_server()->GetURL("/server-redirect?simple.html"),
5378 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195379 LoadStateWithParam load_state = r->GetLoadState();
5380 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515381 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195382 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515383 }
5384
mmenke43758e62015-05-04 21:09:465385 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515386 net_log.GetEntries(&entries);
5387
5388 // Delegate info is always logged in both OnReceivedRedirect and
5389 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5390 // OnResponseStarted delegate call is after cancellation, but logging is
5391 // still currently supported in that call.
5392 size_t log_position = 0;
5393 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485394 if (i == 0) {
5395 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5396 entries, log_position) + 1;
5397 }
5398
[email protected]abe1c4a2013-10-25 19:28:515399 log_position = ExpectLogContainsSomewhereAfter(
5400 entries,
5401 log_position,
5402 NetLog::TYPE_URL_REQUEST_DELEGATE,
5403 NetLog::PHASE_BEGIN);
5404
5405 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5406 log_position + 1);
5407
5408 ASSERT_LT(log_position, entries.size());
5409 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5410 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5411 }
5412
5413 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5414 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5415 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5416 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5417 }
5418}
5419
[email protected]847c0fa92012-11-06 16:37:425420namespace {
5421
5422const char kExtraHeader[] = "Allow-Snafu";
5423const char kExtraValue[] = "fubar";
5424
5425class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205426 void OnReceivedRedirect(URLRequest* request,
5427 const RedirectInfo& redirect_info,
5428 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595429 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425430 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5431 }
5432};
5433
5434} // namespace
5435
5436TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555437 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425438
tommycli59a63432015-11-06 00:10:555439 GURL destination_url =
5440 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5441 GURL original_url =
5442 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425443 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:365444 scoped_ptr<URLRequest> req(
5445 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195446 req->Start();
[email protected]255620da2013-08-19 13:14:295447 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425448
5449 std::string value;
[email protected]f7022f32014-08-21 16:32:195450 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425451 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5452 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195453 EXPECT_FALSE(req->is_pending());
5454 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425455 EXPECT_EQ(kExtraValue, d.data_received());
5456}
5457
[email protected]251a1b92012-11-13 11:01:095458namespace {
5459
5460const char kExtraHeaderToRemove[] = "To-Be-Removed";
5461
5462class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205463 void OnReceivedRedirect(URLRequest* request,
5464 const RedirectInfo& redirect_info,
5465 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595466 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095467 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5468 }
5469};
5470
5471} // namespace
5472
5473TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555474 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095475
tommycli59a63432015-11-06 00:10:555476 GURL destination_url = http_test_server()->GetURL(
5477 "/echoheader?" + std::string(kExtraHeaderToRemove));
5478 GURL original_url =
5479 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095480 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:365481 scoped_ptr<URLRequest> req(
5482 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195483 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5484 req->Start();
[email protected]255620da2013-08-19 13:14:295485 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095486
5487 std::string value;
[email protected]f7022f32014-08-21 16:32:195488 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095489 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195490 EXPECT_FALSE(req->is_pending());
5491 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095492 EXPECT_EQ("None", d.data_received());
5493}
5494
[email protected]316c1e5e2012-09-12 15:17:445495TEST_F(URLRequestTestHTTP, CancelTest) {
5496 TestDelegate d;
5497 {
[email protected]f7022f32014-08-21 16:32:195498 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365499 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445500
[email protected]f7022f32014-08-21 16:32:195501 r->Start();
5502 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445503
[email protected]f7022f32014-08-21 16:32:195504 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445505
[email protected]255620da2013-08-19 13:14:295506 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445507
5508 // We expect to receive OnResponseStarted even though the request has been
5509 // cancelled.
5510 EXPECT_EQ(1, d.response_started_count());
5511 EXPECT_EQ(0, d.bytes_received());
5512 EXPECT_FALSE(d.received_data_before_response());
5513 }
5514}
5515
5516TEST_F(URLRequestTestHTTP, CancelTest2) {
tommycli59a63432015-11-06 00:10:555517 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445518
5519 TestDelegate d;
5520 {
[email protected]f7022f32014-08-21 16:32:195521 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555522 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445523
5524 d.set_cancel_in_response_started(true);
5525
[email protected]f7022f32014-08-21 16:32:195526 r->Start();
5527 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445528
[email protected]255620da2013-08-19 13:14:295529 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445530
5531 EXPECT_EQ(1, d.response_started_count());
5532 EXPECT_EQ(0, d.bytes_received());
5533 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195534 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445535 }
5536}
5537
5538TEST_F(URLRequestTestHTTP, CancelTest3) {
tommycli59a63432015-11-06 00:10:555539 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445540
5541 TestDelegate d;
5542 {
[email protected]f7022f32014-08-21 16:32:195543 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555544 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445545
5546 d.set_cancel_in_received_data(true);
5547
[email protected]f7022f32014-08-21 16:32:195548 r->Start();
5549 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445550
[email protected]255620da2013-08-19 13:14:295551 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445552
5553 EXPECT_EQ(1, d.response_started_count());
5554 // There is no guarantee about how much data was received
5555 // before the cancel was issued. It could have been 0 bytes,
5556 // or it could have been all the bytes.
5557 // EXPECT_EQ(0, d.bytes_received());
5558 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195559 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445560 }
5561}
5562
5563TEST_F(URLRequestTestHTTP, CancelTest4) {
tommycli59a63432015-11-06 00:10:555564 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445565
5566 TestDelegate d;
5567 {
[email protected]f7022f32014-08-21 16:32:195568 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555569 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445570
[email protected]f7022f32014-08-21 16:32:195571 r->Start();
5572 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445573
5574 // The request will be implicitly canceled when it is destroyed. The
5575 // test delegate must not post a quit message when this happens because
5576 // this test doesn't actually have a message loop. The quit message would
5577 // get put on this thread's message queue and the next test would exit
5578 // early, causing problems.
5579 d.set_quit_on_complete(false);
5580 }
5581 // expect things to just cleanup properly.
5582
kimwjdalsl2bb4ff02015-12-16 22:06:025583 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:445584 // message loop
5585 EXPECT_FALSE(d.received_data_before_response());
5586 EXPECT_EQ(0, d.bytes_received());
5587}
5588
5589TEST_F(URLRequestTestHTTP, CancelTest5) {
tommycli59a63432015-11-06 00:10:555590 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445591
5592 // populate cache
5593 {
5594 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195595 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555596 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195597 r->Start();
[email protected]255620da2013-08-19 13:14:295598 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195599 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445600 }
5601
5602 // cancel read from cache (see bug 990242)
5603 {
5604 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195605 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555606 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195607 r->Start();
5608 r->Cancel();
[email protected]255620da2013-08-19 13:14:295609 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445610
[email protected]f7022f32014-08-21 16:32:195611 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445612 EXPECT_EQ(1, d.response_started_count());
5613 EXPECT_EQ(0, d.bytes_received());
5614 EXPECT_FALSE(d.received_data_before_response());
5615 }
5616}
5617
5618TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:555619 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445620 HTTPUploadDataOperationTest("POST");
5621}
5622
5623TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:555624 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445625 HTTPUploadDataOperationTest("PUT");
5626}
5627
5628TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:555629 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445630
5631 TestDelegate d;
5632 {
[email protected]f7022f32014-08-21 16:32:195633 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555634 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195635 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445636
[email protected]f7022f32014-08-21 16:32:195637 r->Start();
5638 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445639
[email protected]255620da2013-08-19 13:14:295640 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445641
[email protected]329b68b2012-11-14 17:54:275642 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195643 << "request failed: " << r->status().status()
5644 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445645
5646 EXPECT_FALSE(d.received_data_before_response());
5647 EXPECT_TRUE(d.data_received().empty());
5648 }
5649}
5650
5651TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:555652 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445653
5654 TestDelegate d;
5655 {
[email protected]f7022f32014-08-21 16:32:195656 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555657 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195658 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445659
[email protected]6cdfd7f2013-02-08 20:40:155660 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445661 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025662 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445663
olli.raula6df48b2a2015-11-26 07:40:225664 std::vector<scoped_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445665
[email protected]6cdfd7f2013-02-08 20:40:155666 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445667 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475668 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445669 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
avibf0746c2015-12-09 19:53:145670 element_readers.push_back(make_scoped_ptr(new UploadFileElementReader(
5671 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
5672 std::numeric_limits<uint64_t>::max(), base::Time())));
mmenkecbc2b712014-10-09 20:29:075673 r->set_upload(make_scoped_ptr<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225674 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:445675
[email protected]f7022f32014-08-21 16:32:195676 r->Start();
5677 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445678
[email protected]255620da2013-08-19 13:14:295679 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445680
avibf0746c2015-12-09 19:53:145681 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:295682 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5683 ASSERT_LE(size64, std::numeric_limits<int>::max());
5684 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175685 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445686
[email protected]7600d0b2013-12-08 21:43:305687 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445688
[email protected]329b68b2012-11-14 17:54:275689 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195690 << "request failed: " << r->status().status()
5691 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445692
5693 EXPECT_FALSE(d.received_data_before_response());
5694
[email protected]329b68b2012-11-14 17:54:275695 EXPECT_EQ(size, d.bytes_received());
5696 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445697 }
5698}
5699
[email protected]999dd8c2013-11-12 06:45:545700TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:555701 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:545702
5703 TestDelegate d;
5704 {
[email protected]f7022f32014-08-21 16:32:195705 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555706 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195707 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545708
olli.raula6df48b2a2015-11-26 07:40:225709 std::vector<scoped_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:545710
olli.raula6df48b2a2015-11-26 07:40:225711 element_readers.push_back(make_scoped_ptr(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455712 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545713 base::FilePath(FILE_PATH_LITERAL(
5714 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
avibf0746c2015-12-09 19:53:145715 0, std::numeric_limits<uint64_t>::max(), base::Time())));
mmenkecbc2b712014-10-09 20:29:075716 r->set_upload(make_scoped_ptr<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225717 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:545718
[email protected]f7022f32014-08-21 16:32:195719 r->Start();
5720 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545721
5722 base::RunLoop().Run();
5723
[email protected]999dd8c2013-11-12 06:45:545724 EXPECT_TRUE(d.request_failed());
5725 EXPECT_FALSE(d.received_data_before_response());
5726 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195727 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5728 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545729 }
5730}
5731
[email protected]316c1e5e2012-09-12 15:17:445732TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:555733 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445734
5735 TestDelegate d;
5736 {
[email protected]f7022f32014-08-21 16:32:195737 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555738 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195739 r->EnableChunkedUpload();
5740 r->set_method("POST");
5741 AddChunksToUpload(r.get());
5742 r->Start();
5743 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445744
[email protected]255620da2013-08-19 13:14:295745 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445746
[email protected]f7022f32014-08-21 16:32:195747 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445748 }
5749}
5750
[email protected]329b68b2012-11-14 17:54:275751TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:555752 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:275753
5754 TestDelegate d;
5755 {
[email protected]f7022f32014-08-21 16:32:195756 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555757 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195758 r->EnableChunkedUpload();
5759 r->set_method("POST");
5760 r->Start();
5761 EXPECT_TRUE(r->is_pending());
5762 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295763 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275764
[email protected]f7022f32014-08-21 16:32:195765 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275766 }
5767}
5768
[email protected]316c1e5e2012-09-12 15:17:445769TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:555770 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445771
5772 TestDelegate d;
5773 {
[email protected]f7022f32014-08-21 16:32:195774 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555775 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195776 r->EnableChunkedUpload();
5777 r->set_method("POST");
5778 r->Start();
5779 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445780
[email protected]255620da2013-08-19 13:14:295781 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195782 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295783 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445784
[email protected]f7022f32014-08-21 16:32:195785 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445786 }
5787}
5788
5789TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:555790 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445791
5792 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195793 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555794 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195795 req->Start();
[email protected]255620da2013-08-19 13:14:295796 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445797
[email protected]f7022f32014-08-21 16:32:195798 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445799
5800 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195801 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445802
5803 std::string header;
5804 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5805 EXPECT_EQ("private", header);
5806
5807 header.clear();
5808 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5809 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5810
5811 // The response has two "X-Multiple-Entries" headers.
5812 // This verfies our output has them concatenated together.
5813 header.clear();
5814 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5815 EXPECT_EQ("a, b", header);
5816}
5817
tommycli59a63432015-11-06 00:10:555818// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
5819// security state. (see http://crbug.com/550977).
5820#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:465821TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:555822 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5823 https_test_server.SetSSLConfig(
5824 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5825 https_test_server.ServeFilesFromSourceDirectory(
5826 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465827 ASSERT_TRUE(https_test_server.Start());
5828
tommycli59a63432015-11-06 00:10:555829 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:465830 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195831 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555832 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195833 request->Start();
[email protected]255620da2013-08-19 13:14:295834 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465835
5836 TransportSecurityState* security_state =
5837 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405838 TransportSecurityState::STSState sts_state;
5839 TransportSecurityState::PKPState pkp_state;
5840 EXPECT_TRUE(
5841 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5842 EXPECT_FALSE(
5843 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5844 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5845 sts_state.upgrade_mode);
5846 EXPECT_TRUE(sts_state.include_subdomains);
5847 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:035848#if defined(OS_ANDROID)
5849 // Android's CertVerifyProc does not (yet) handle pins.
5850#else
martijnc0d6b622015-06-30 19:14:405851 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035852#endif
[email protected]37fd55fb2013-06-29 13:13:275853}
5854
estarka5da76702015-04-09 04:00:165855TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555856 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5857 https_test_server.ServeFilesFromSourceDirectory(
5858 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165859 ASSERT_TRUE(https_test_server.Start());
5860 // Make sure this test fails if the test server is changed to not
5861 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555862 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5863 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165864
5865 TestDelegate d;
5866 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555867 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:165868 request->Start();
5869 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:165870 TransportSecurityState* security_state =
5871 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405872 TransportSecurityState::STSState sts_state;
5873 EXPECT_FALSE(
5874 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165875}
5876
mathpc992e602015-10-21 20:34:035877// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5878// reject HPKP headers, and a test setting only HPKP headers will fail (no
5879// PKPState present because header rejected).
5880#if defined(OS_ANDROID)
5881#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5882#define MAYBE_ProcessPKPAndSendReport DISABLED_ProcessPKPAndSendReport
5883#define MAYBE_ProcessPKPReportOnly DISABLED_ProcessPKPReportOnly
5884#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5885 DISABLED_ProcessPKPReportOnlyWithNoViolation
5886#else
5887#define MAYBE_ProcessPKP ProcessPKP
5888#define MAYBE_ProcessPKPAndSendReport ProcessPKPAndSendReport
5889#define MAYBE_ProcessPKPReportOnly ProcessPKPReportOnly
5890#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5891 ProcessPKPReportOnlyWithNoViolation
5892#endif
5893
estark06e0dac2015-08-07 21:56:015894namespace {
5895const char kHPKPReportUri[] = "https://hpkp-report.test";
5896} // namespace
5897
[email protected]37fd55fb2013-06-29 13:13:275898// Tests that enabling HPKP on a domain does not affect the HSTS
5899// validity/expiration.
mathpc992e602015-10-21 20:34:035900TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estark06e0dac2015-08-07 21:56:015901 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555902 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5903 https_test_server.SetSSLConfig(
5904 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5905 https_test_server.ServeFilesFromSourceDirectory(
5906 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275907 ASSERT_TRUE(https_test_server.Start());
5908
tommycli59a63432015-11-06 00:10:555909 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165910
[email protected]37fd55fb2013-06-29 13:13:275911 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195912 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555913 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195914 request->Start();
[email protected]255620da2013-08-19 13:14:295915 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275916 TransportSecurityState* security_state =
5917 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405918 TransportSecurityState::STSState sts_state;
5919 TransportSecurityState::PKPState pkp_state;
5920 EXPECT_FALSE(
5921 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5922 EXPECT_TRUE(
5923 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5924 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
5925 sts_state.upgrade_mode);
5926 EXPECT_FALSE(sts_state.include_subdomains);
5927 EXPECT_FALSE(pkp_state.include_subdomains);
5928 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:015929 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:405930 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:465931}
5932
estark06e0dac2015-08-07 21:56:015933// Tests that reports get sent on HPKP violations when a report-uri is set.
mathpc992e602015-10-21 20:34:035934TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:015935 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555936 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5937 https_test_server.SetSSLConfig(
5938 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5939 https_test_server.ServeFilesFromSourceDirectory(
5940 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015941 ASSERT_TRUE(https_test_server.Start());
5942
tommycli59a63432015-11-06 00:10:555943 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015944
5945 // Set up a pin for |test_server_hostname|.
5946 TransportSecurityState security_state;
5947 const base::Time current_time(base::Time::Now());
5948 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
5949 HashValueVector hashes;
5950 HashValue hash1;
5951 HashValue hash2;
5952 // The values here don't matter, as long as they are different from
5953 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:445954 ASSERT_TRUE(
5955 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
5956 ASSERT_TRUE(
5957 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:015958 hashes.push_back(hash1);
5959 hashes.push_back(hash2);
5960 security_state.AddHPKP(test_server_hostname, expiry,
5961 false, /* include subdomains */
5962 hashes, report_uri);
5963
5964 MockCertificateReportSender mock_report_sender;
5965 security_state.SetReportSender(&mock_report_sender);
5966
5967 // Set up a MockCertVerifier to trigger a violation of the previously
5968 // set pin.
5969 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
5970 ASSERT_TRUE(cert);
5971
5972 MockCertVerifier cert_verifier;
5973 CertVerifyResult verify_result;
5974 verify_result.verified_cert = cert;
5975 verify_result.is_issued_by_known_root = true;
5976 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:445977 ASSERT_TRUE(
5978 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:015979 verify_result.public_key_hashes.push_back(hash3);
5980 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
5981
5982 TestNetworkDelegate network_delegate;
5983 TestURLRequestContext context(true);
5984 context.set_transport_security_state(&security_state);
5985 context.set_network_delegate(&network_delegate);
5986 context.set_cert_verifier(&cert_verifier);
5987 context.Init();
5988
5989 // Now send a request to trigger the violation.
5990 TestDelegate d;
5991 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555992 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
estark06e0dac2015-08-07 21:56:015993 violating_request->Start();
5994 base::RunLoop().Run();
5995
5996 // Check that a report was sent.
5997 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
5998 ASSERT_FALSE(mock_report_sender.latest_report().empty());
5999 scoped_ptr<base::Value> value(
6000 base::JSONReader::Read(mock_report_sender.latest_report()));
6001 ASSERT_TRUE(value);
6002 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6003 base::DictionaryValue* report_dict;
6004 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6005 std::string report_hostname;
6006 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6007 EXPECT_EQ(test_server_hostname, report_hostname);
6008}
6009
6010// Tests that reports get sent on requests with
6011// Public-Key-Pins-Report-Only headers.
mathpc992e602015-10-21 20:34:036012TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016013 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556014 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6015 https_test_server.SetSSLConfig(
6016 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6017 https_test_server.ServeFilesFromSourceDirectory(
6018 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016019 ASSERT_TRUE(https_test_server.Start());
6020
tommycli59a63432015-11-06 00:10:556021 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016022
6023 TransportSecurityState security_state;
6024 MockCertificateReportSender mock_report_sender;
6025 security_state.SetReportSender(&mock_report_sender);
6026
6027 // Set up a MockCertVerifier to violate the pin in the Report-Only
6028 // header.
6029 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6030 ASSERT_TRUE(cert);
6031
6032 MockCertVerifier cert_verifier;
6033 CertVerifyResult verify_result;
6034 verify_result.verified_cert = cert;
6035 verify_result.is_issued_by_known_root = true;
6036 HashValue hash;
6037 // This value doesn't matter, as long as it is different from the pins
6038 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446039 ASSERT_TRUE(
6040 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016041 verify_result.public_key_hashes.push_back(hash);
6042 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6043
6044 TestNetworkDelegate network_delegate;
6045 TestURLRequestContext context(true);
6046 context.set_transport_security_state(&security_state);
6047 context.set_network_delegate(&network_delegate);
6048 context.set_cert_verifier(&cert_verifier);
6049 context.Init();
6050
6051 // Now send a request to trigger the violation.
6052 TestDelegate d;
6053 scoped_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556054 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016055 DEFAULT_PRIORITY, &d));
6056 violating_request->Start();
6057 base::RunLoop().Run();
6058
6059 // Check that a report was sent.
6060 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6061 ASSERT_FALSE(mock_report_sender.latest_report().empty());
6062 scoped_ptr<base::Value> value(
6063 base::JSONReader::Read(mock_report_sender.latest_report()));
6064 ASSERT_TRUE(value);
6065 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6066 base::DictionaryValue* report_dict;
6067 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6068 std::string report_hostname;
6069 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6070 EXPECT_EQ(test_server_hostname, report_hostname);
6071}
6072
6073// Tests that reports do not get sent on requests with
6074// Public-Key-Pins-Report-Only headers that don't have pin violations.
mathpc992e602015-10-21 20:34:036075TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016076 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556077 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6078 https_test_server.SetSSLConfig(
6079 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6080 https_test_server.ServeFilesFromSourceDirectory(
6081 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016082 ASSERT_TRUE(https_test_server.Start());
6083
tommycli59a63432015-11-06 00:10:556084 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016085
6086 TransportSecurityState security_state;
6087 MockCertificateReportSender mock_report_sender;
6088 security_state.SetReportSender(&mock_report_sender);
6089
6090 TestNetworkDelegate network_delegate;
6091 MockCertVerifier mock_cert_verifier;
6092 TestURLRequestContext context(true);
6093 context.set_transport_security_state(&security_state);
6094 context.set_network_delegate(&network_delegate);
6095 context.set_cert_verifier(&mock_cert_verifier);
6096 mock_cert_verifier.set_default_result(OK);
6097 context.Init();
6098
6099 // Now send a request that does not trigger the violation.
6100 TestDelegate d;
6101 scoped_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556102 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016103 DEFAULT_PRIORITY, &d));
6104 request->Start();
6105 base::RunLoop().Run();
6106
6107 // Check that a report was not sent.
6108 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6109 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6110}
6111
estarka5da76702015-04-09 04:00:166112TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556113 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6114 https_test_server.ServeFilesFromSourceDirectory(
6115 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166116 ASSERT_TRUE(https_test_server.Start());
6117 // Make sure this test fails if the test server is changed to not
6118 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556119 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6120 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166121
6122 TestDelegate d;
6123 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556124 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:166125 request->Start();
6126 base::RunLoop().Run();
6127
6128 TransportSecurityState* security_state =
6129 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406130 TransportSecurityState::PKPState pkp_state;
6131 EXPECT_FALSE(
6132 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166133}
6134
[email protected]242d8562012-10-30 21:20:466135TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556136 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6137 https_test_server.SetSSLConfig(
6138 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6139 https_test_server.ServeFilesFromSourceDirectory(
6140 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466141 ASSERT_TRUE(https_test_server.Start());
6142
tommycli59a63432015-11-06 00:10:556143 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166144
[email protected]242d8562012-10-30 21:20:466145 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196146 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556147 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
6148 &d));
[email protected]f7022f32014-08-21 16:32:196149 request->Start();
[email protected]255620da2013-08-19 13:14:296150 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466151
6152 // We should have set parameters from the first header, not the second.
6153 TransportSecurityState* security_state =
6154 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406155 TransportSecurityState::STSState sts_state;
6156 EXPECT_TRUE(
6157 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6158 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6159 sts_state.upgrade_mode);
6160 EXPECT_FALSE(sts_state.include_subdomains);
6161 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466162}
6163
[email protected]9f972ec2013-04-10 20:24:366164TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556165 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6166 https_test_server.SetSSLConfig(
6167 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6168 https_test_server.ServeFilesFromSourceDirectory(
6169 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366170 ASSERT_TRUE(https_test_server.Start());
6171
tommycli59a63432015-11-06 00:10:556172 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166173
[email protected]9f972ec2013-04-10 20:24:366174 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196175 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556176 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
6177 &d));
[email protected]f7022f32014-08-21 16:32:196178 request->Start();
[email protected]255620da2013-08-19 13:14:296179 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366180
6181 // We should have set parameters from the first header, not the second.
6182 TransportSecurityState* security_state =
6183 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406184 TransportSecurityState::STSState sts_state;
6185 TransportSecurityState::PKPState pkp_state;
6186 EXPECT_TRUE(
6187 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6188 EXPECT_TRUE(
6189 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6190 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6191 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036192#if defined(OS_ANDROID)
6193 // Android's CertVerifyProc does not (yet) handle pins.
6194#else
martijnc0d6b622015-06-30 19:14:406195 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036196#endif
martijnc0d6b622015-06-30 19:14:406197 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366198
[email protected]a165f092013-06-12 16:10:056199 // Even though there is an HSTS header asserting includeSubdomains, it is
6200 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406201 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056202 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406203 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366204}
6205
[email protected]37fd55fb2013-06-29 13:13:276206// Tests that when multiple HPKP headers are present, asserting different
6207// policies, that only the first such policy is processed.
6208TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556209 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6210 https_test_server.SetSSLConfig(
6211 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6212 https_test_server.ServeFilesFromSourceDirectory(
6213 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276214 ASSERT_TRUE(https_test_server.Start());
6215
tommycli59a63432015-11-06 00:10:556216 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166217
[email protected]37fd55fb2013-06-29 13:13:276218 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196219 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556220 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:366221 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196222 request->Start();
[email protected]255620da2013-08-19 13:14:296223 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276224
6225 TransportSecurityState* security_state =
6226 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406227 TransportSecurityState::STSState sts_state;
6228 TransportSecurityState::PKPState pkp_state;
6229 EXPECT_TRUE(
6230 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6231 EXPECT_TRUE(
6232 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6233 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6234 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036235#if defined(OS_ANDROID)
6236 // Android's CertVerifyProc does not (yet) handle pins.
6237#else
martijnc0d6b622015-06-30 19:14:406238 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036239#endif
martijnc0d6b622015-06-30 19:14:406240 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276241
martijnc0d6b622015-06-30 19:14:406242 EXPECT_TRUE(sts_state.include_subdomains);
6243 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276244}
6245
tommycli59a63432015-11-06 00:10:556246#endif // !defined(OS_IOS)
6247
[email protected]316c1e5e2012-09-12 15:17:446248TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:556249 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446250
6251 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196252 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556253 http_test_server()->GetURL("/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366254 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196255 req->Start();
[email protected]255620da2013-08-19 13:14:296256 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446257
6258 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196259 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446260 EXPECT_EQ("text/html", mime_type);
6261
6262 std::string charset;
[email protected]f7022f32014-08-21 16:32:196263 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446264 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196265 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446266}
6267
[email protected]02494ec2014-05-07 15:05:296268TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346269 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346270 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346271 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026272 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346273
6274 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506275 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346276}
6277
[email protected]02494ec2014-05-07 15:05:296278#if !defined(DISABLE_FILE_SUPPORT)
6279TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6280 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6281 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456282 FileProtocolHandler file_protocol_handler(
6283 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296284 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6285
6286 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506287 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296288}
6289
[email protected]588614c22013-08-16 00:09:026290TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:556291 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446292
6293 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196294 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556295 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366296 &d));
[email protected]f7022f32014-08-21 16:32:196297 req->Start();
[email protected]255620da2013-08-19 13:14:296298 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446299
[email protected]f7022f32014-08-21 16:32:196300 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6301 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446302}
[email protected]02494ec2014-05-07 15:05:296303#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446304
[email protected]588614c22013-08-16 00:09:026305TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:556306 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:026307
6308 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196309 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556310 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366311 &d));
[email protected]f7022f32014-08-21 16:32:196312 req->Start();
[email protected]588614c22013-08-16 00:09:026313 base::MessageLoop::current()->Run();
6314
[email protected]f7022f32014-08-21 16:32:196315 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6316 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:026317}
6318
[email protected]316c1e5e2012-09-12 15:17:446319TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:556320 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446321
6322 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196323 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556324 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366325 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196326 req->Start();
[email protected]255620da2013-08-19 13:14:296327 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446328
[email protected]f7022f32014-08-21 16:32:196329 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6330 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446331}
6332
[email protected]e50efea2014-03-24 18:41:006333// Make sure redirects are cached, despite not reading their bodies.
6334TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:556335 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006336 GURL redirect_url =
tommycli59a63432015-11-06 00:10:556337 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:006338
6339 {
6340 TestDelegate d;
davidben151423e2015-03-23 18:48:366341 scoped_ptr<URLRequest> req(
6342 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196343 req->Start();
[email protected]e50efea2014-03-24 18:41:006344 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196345 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006346 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:556347 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006348 }
6349
6350 {
6351 TestDelegate d;
6352 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:366353 scoped_ptr<URLRequest> req(
6354 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196355 req->Start();
[email protected]e50efea2014-03-24 18:41:006356 base::RunLoop().Run();
6357
6358 EXPECT_EQ(1, d.received_redirect_count());
6359 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196360 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006361
[email protected]f7022f32014-08-21 16:32:196362 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006363 base::RunLoop().Run();
6364 EXPECT_EQ(1, d.received_redirect_count());
6365 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196366 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
tommycli59a63432015-11-06 00:10:556367 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006368 }
6369}
6370
6371// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6372// when the headers are read, since the body won't have been read.
6373TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:556374 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006375 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:556376 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:006377
6378 {
6379 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:556380 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:006381 default_network_delegate_.set_redirect_on_headers_received_url(
6382 redirect_to_url);
6383
6384 TestDelegate d;
davidben151423e2015-03-23 18:48:366385 scoped_ptr<URLRequest> req(
6386 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196387 req->Start();
[email protected]e50efea2014-03-24 18:41:006388 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196389 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006390 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196391 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006392 }
6393
6394 {
6395 TestDelegate d;
davidben151423e2015-03-23 18:48:366396 scoped_ptr<URLRequest> req(
6397 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196398 req->Start();
[email protected]e50efea2014-03-24 18:41:006399 base::RunLoop().Run();
6400
[email protected]f7022f32014-08-21 16:32:196401 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6402 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006403 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196404 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006405 }
6406}
6407
[email protected]5f714132014-03-26 10:41:166408// Tests that redirection to an unsafe URL is allowed when it has been marked as
6409// safe.
6410TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:556411 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166412
6413 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6414 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6415 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6416
6417 TestDelegate d;
6418 {
[email protected]f7022f32014-08-21 16:32:196419 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556420 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166421
[email protected]f7022f32014-08-21 16:32:196422 r->Start();
[email protected]5f714132014-03-26 10:41:166423 base::RunLoop().Run();
6424
[email protected]f7022f32014-08-21 16:32:196425 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:166426
[email protected]f7022f32014-08-21 16:32:196427 EXPECT_EQ(2U, r->url_chain().size());
6428 EXPECT_EQ(OK, r->status().error());
6429 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166430 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6431 }
6432}
6433
6434// Tests that a redirect to a different unsafe URL is blocked, even after adding
6435// some other URL to the whitelist.
6436TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:556437 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166438
6439 GURL unsafe_url("data:text/html,something");
6440 GURL different_unsafe_url("data:text/html,something-else");
6441 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6442 default_network_delegate_.set_allowed_unsafe_redirect_url(
6443 different_unsafe_url);
6444
6445 TestDelegate d;
6446 {
[email protected]f7022f32014-08-21 16:32:196447 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556448 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166449
[email protected]f7022f32014-08-21 16:32:196450 r->Start();
[email protected]5f714132014-03-26 10:41:166451 base::RunLoop().Run();
6452
[email protected]f7022f32014-08-21 16:32:196453 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
6454 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:166455 }
6456}
6457
[email protected]5f714132014-03-26 10:41:166458// Redirects from an URL with fragment to an unsafe URL with fragment should
6459// be allowed, and the reference fragment of the target URL should be preserved.
6460TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:556461 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166462
tommycli59a63432015-11-06 00:10:556463 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:166464 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6465 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6466
6467 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6468 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6469
6470 TestDelegate d;
6471 {
davidben151423e2015-03-23 18:48:366472 scoped_ptr<URLRequest> r(
6473 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166474
[email protected]f7022f32014-08-21 16:32:196475 r->Start();
[email protected]5f714132014-03-26 10:41:166476 base::RunLoop().Run();
6477
[email protected]f7022f32014-08-21 16:32:196478 EXPECT_EQ(2U, r->url_chain().size());
6479 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6480 EXPECT_EQ(OK, r->status().error());
6481 EXPECT_EQ(original_url, r->original_url());
6482 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166483 }
6484}
6485
6486// When a delegate has specified a safe redirect URL, but it does not match the
6487// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146488TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:556489 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166490
tommycli59a63432015-11-06 00:10:556491 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166492 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:556493 GURL redirect_url(http_test_server()->GetURL("/target"));
6494 GURL expected_redirect_url(
6495 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166496
6497 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6498 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6499
6500 TestDelegate d;
6501 {
davidben151423e2015-03-23 18:48:366502 scoped_ptr<URLRequest> r(
6503 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166504
[email protected]f7022f32014-08-21 16:32:196505 r->Start();
[email protected]5f714132014-03-26 10:41:166506 base::RunLoop().Run();
6507
[email protected]f7022f32014-08-21 16:32:196508 EXPECT_EQ(2U, r->url_chain().size());
6509 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6510 EXPECT_EQ(OK, r->status().error());
6511 EXPECT_EQ(original_url, r->original_url());
6512 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166513 }
6514}
6515
[email protected]f878230e2014-04-03 15:36:146516// When a delegate has specified a safe redirect URL, assume that the redirect
6517// URL should not be changed. In particular, the reference fragment should not
6518// be modified.
6519TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556520 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146521
tommycli59a63432015-11-06 00:10:556522 GURL original_url(
6523 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:146524 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6525
6526 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6527 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6528
6529 TestDelegate d;
6530 {
davidben151423e2015-03-23 18:48:366531 scoped_ptr<URLRequest> r(
6532 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146533
[email protected]f7022f32014-08-21 16:32:196534 r->Start();
[email protected]f878230e2014-04-03 15:36:146535 base::RunLoop().Run();
6536
[email protected]f7022f32014-08-21 16:32:196537 EXPECT_EQ(2U, r->url_chain().size());
6538 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6539 EXPECT_EQ(OK, r->status().error());
6540 EXPECT_EQ(original_url, r->original_url());
6541 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146542 }
6543}
6544
6545// When a URLRequestRedirectJob is created, the redirection must be followed and
6546// the reference fragment of the target URL must not be modified.
6547TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556548 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146549
tommycli59a63432015-11-06 00:10:556550 GURL original_url(
6551 http_test_server()->GetURL("/original#should-not-be-appended"));
6552 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:146553
6554 TestDelegate d;
davidben151423e2015-03-23 18:48:366555 scoped_ptr<URLRequest> r(
6556 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146557
mmenkeed0498b2015-12-08 23:20:426558 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196559 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:426560 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
6561 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:146562
[email protected]f7022f32014-08-21 16:32:196563 r->Start();
[email protected]f878230e2014-04-03 15:36:146564 base::RunLoop().Run();
6565
[email protected]f7022f32014-08-21 16:32:196566 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6567 EXPECT_EQ(OK, r->status().error());
6568 EXPECT_EQ(original_url, r->original_url());
6569 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146570}
6571
[email protected]316c1e5e2012-09-12 15:17:446572TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:556573 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446574
6575 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196576 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556577 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196578 req->SetReferrer("http://user:[email protected]/");
6579 req->Start();
[email protected]255620da2013-08-19 13:14:296580 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446581
6582 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6583}
6584
[email protected]99ecf6e2013-04-10 22:46:136585TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:556586 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136587
6588 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196589 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556590 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196591 req->SetReferrer("http://foo.com/test#fragment");
6592 req->Start();
[email protected]255620da2013-08-19 13:14:296593 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136594
6595 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6596}
6597
6598TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:556599 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136600
6601 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196602 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556603 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196604 req->SetReferrer("http://foo.com/test#fragment");
6605 req->SetReferrer("");
6606 req->Start();
[email protected]255620da2013-08-19 13:14:296607 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136608
6609 EXPECT_EQ(std::string("None"), d.data_received());
6610}
6611
[email protected]1826a402014-01-08 15:40:486612// Defer network start and then resume, checking that the request was a success
6613// and bytes were received.
6614TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556615 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486616
6617 TestDelegate d;
6618 {
6619 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556620 GURL test_url(http_test_server()->GetURL("/echo"));
davidben151423e2015-03-23 18:48:366621 scoped_ptr<URLRequest> req(
6622 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486623
[email protected]f7022f32014-08-21 16:32:196624 req->Start();
[email protected]1826a402014-01-08 15:40:486625 base::RunLoop().Run();
6626
6627 EXPECT_EQ(1, d.received_before_network_start_count());
6628 EXPECT_EQ(0, d.response_started_count());
6629
[email protected]f7022f32014-08-21 16:32:196630 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486631 base::RunLoop().Run();
6632
6633 EXPECT_EQ(1, d.response_started_count());
6634 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196635 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486636 }
6637}
6638
6639// Check that OnBeforeNetworkStart is only called once even if there is a
6640// redirect.
6641TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
tommycli59a63432015-11-06 00:10:556642 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486643
6644 TestDelegate d;
6645 {
6646 d.set_quit_on_redirect(true);
6647 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:196648 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556649 http_test_server()->GetURL("/server-redirect?echo"), DEFAULT_PRIORITY,
6650 &d));
[email protected]1826a402014-01-08 15:40:486651
[email protected]f7022f32014-08-21 16:32:196652 req->Start();
[email protected]1826a402014-01-08 15:40:486653 base::RunLoop().Run();
6654
6655 EXPECT_EQ(1, d.received_before_network_start_count());
6656 EXPECT_EQ(0, d.response_started_count());
6657 EXPECT_EQ(0, d.received_redirect_count());
6658
[email protected]f7022f32014-08-21 16:32:196659 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486660 base::RunLoop().Run();
6661
6662 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196663 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:486664 base::RunLoop().Run();
6665
6666 // Check that the redirect's new network transaction does not get propagated
6667 // to a second OnBeforeNetworkStart() notification.
6668 EXPECT_EQ(1, d.received_before_network_start_count());
6669
6670 EXPECT_EQ(1, d.response_started_count());
6671 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196672 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486673 }
6674}
6675
6676// Cancel the request after learning that the request would use the network.
6677TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556678 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486679
6680 TestDelegate d;
6681 {
6682 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556683 GURL test_url(http_test_server()->GetURL("/echo"));
davidben151423e2015-03-23 18:48:366684 scoped_ptr<URLRequest> req(
6685 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486686
[email protected]f7022f32014-08-21 16:32:196687 req->Start();
[email protected]1826a402014-01-08 15:40:486688 base::RunLoop().Run();
6689
6690 EXPECT_EQ(1, d.received_before_network_start_count());
6691 EXPECT_EQ(0, d.response_started_count());
6692
[email protected]f7022f32014-08-21 16:32:196693 req->Cancel();
[email protected]1826a402014-01-08 15:40:486694 base::RunLoop().Run();
6695
6696 EXPECT_EQ(1, d.response_started_count());
6697 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196698 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:486699 }
6700}
6701
[email protected]316c1e5e2012-09-12 15:17:446702TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:556703 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446704
6705 TestDelegate d;
6706 {
6707 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:196708 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556709 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6710 &d));
[email protected]f7022f32014-08-21 16:32:196711 req->Start();
[email protected]255620da2013-08-19 13:14:296712 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446713
6714 EXPECT_EQ(1, d.response_started_count());
6715 EXPECT_EQ(0, d.bytes_received());
6716 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196717 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446718 }
6719}
6720
6721TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:556722 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446723
6724 TestDelegate d;
6725 {
6726 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556727 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
davidben151423e2015-03-23 18:48:366728 scoped_ptr<URLRequest> req(
6729 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046730
[email protected]f7022f32014-08-21 16:32:196731 req->Start();
[email protected]255620da2013-08-19 13:14:296732 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446733
6734 EXPECT_EQ(1, d.received_redirect_count());
6735
[email protected]f7022f32014-08-21 16:32:196736 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296737 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446738
6739 EXPECT_EQ(1, d.response_started_count());
6740 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196741 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446742
[email protected]6cdfd7f2013-02-08 20:40:156743 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446744 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476745 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446746 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6747
6748 std::string contents;
[email protected]82f84b92013-08-30 18:23:506749 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446750 EXPECT_EQ(contents, d.data_received());
6751 }
6752}
6753
[email protected]79e1fd62013-06-20 06:50:046754TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:556755 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:046756
6757 TestDelegate d;
6758 {
6759 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556760 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
davidben151423e2015-03-23 18:48:366761 scoped_ptr<URLRequest> req(
6762 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046763
6764 EXPECT_FALSE(d.have_full_request_headers());
6765
[email protected]f7022f32014-08-21 16:32:196766 req->Start();
[email protected]255620da2013-08-19 13:14:296767 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046768
6769 EXPECT_EQ(1, d.received_redirect_count());
6770 EXPECT_TRUE(d.have_full_request_headers());
6771 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6772 d.ClearFullRequestHeaders();
6773
[email protected]f7022f32014-08-21 16:32:196774 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296775 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046776
tommycli59a63432015-11-06 00:10:556777 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:046778 EXPECT_EQ(1, d.response_started_count());
6779 EXPECT_TRUE(d.have_full_request_headers());
6780 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6781 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196782 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046783
6784 base::FilePath path;
6785 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476786 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046787 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6788
6789 std::string contents;
[email protected]82f84b92013-08-30 18:23:506790 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046791 EXPECT_EQ(contents, d.data_received());
6792 }
6793}
6794
[email protected]316c1e5e2012-09-12 15:17:446795TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:556796 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446797
6798 TestDelegate d;
6799 {
6800 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196801 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556802 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6803 &d));
[email protected]f7022f32014-08-21 16:32:196804 req->Start();
[email protected]255620da2013-08-19 13:14:296805 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446806
6807 EXPECT_EQ(1, d.received_redirect_count());
6808
[email protected]f7022f32014-08-21 16:32:196809 req->Cancel();
[email protected]255620da2013-08-19 13:14:296810 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446811
6812 EXPECT_EQ(1, d.response_started_count());
6813 EXPECT_EQ(0, d.bytes_received());
6814 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196815 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446816 }
6817}
6818
6819TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:556820 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446821
[email protected]3b23a222013-05-15 21:33:256822 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446823 {
6824 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196825 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556826 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6827 &d));
[email protected]316c1e5e2012-09-12 15:17:446828 HttpRequestHeaders headers;
6829 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196830 req->SetExtraRequestHeaders(headers);
6831 req->Start();
[email protected]255620da2013-08-19 13:14:296832 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256833
6834 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196835 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256836 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446837 }
6838
[email protected]3b23a222013-05-15 21:33:256839 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446840 {
6841 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196842 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556843 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6844 &d));
[email protected]316c1e5e2012-09-12 15:17:446845 HttpRequestHeaders headers;
6846 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196847 req->SetExtraRequestHeaders(headers);
6848 req->Start();
[email protected]255620da2013-08-19 13:14:296849 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446850
[email protected]f7022f32014-08-21 16:32:196851 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256852
6853 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196854 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256855 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446856 }
6857
[email protected]3b23a222013-05-15 21:33:256858 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446859 {
6860 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196861 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556862 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6863 &d));
[email protected]316c1e5e2012-09-12 15:17:446864 HttpRequestHeaders headers;
6865 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196866 req->SetExtraRequestHeaders(headers);
6867 req->Start();
[email protected]255620da2013-08-19 13:14:296868 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446869
[email protected]f7022f32014-08-21 16:32:196870 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256871
6872 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196873 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256874 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446875 }
6876}
6877
6878TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:556879 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446880
6881 // populate the cache
6882 {
6883 TestDelegate d;
6884 d.set_credentials(AuthCredentials(kUser, kSecret));
6885
[email protected]f7022f32014-08-21 16:32:196886 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556887 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196888 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446889
[email protected]255620da2013-08-19 13:14:296890 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446891
6892 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6893 }
6894
6895 // repeat request with end-to-end validation. since auth-basic results in a
6896 // cachable page, we expect this test to result in a 304. in which case, the
6897 // response should be fetched from the cache.
6898 {
6899 TestDelegate d;
6900 d.set_credentials(AuthCredentials(kUser, kSecret));
6901
[email protected]f7022f32014-08-21 16:32:196902 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556903 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196904 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6905 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446906
[email protected]255620da2013-08-19 13:14:296907 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446908
6909 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6910
6911 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196912 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446913 }
6914}
6915
6916// Check that Set-Cookie headers in 401 responses are respected.
6917// http://crbug.com/6450
6918TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:556919 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446920
6921 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:556922 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:446923
6924 // Request a page that will give a 401 containing a Set-Cookie header.
6925 // Verify that when the transaction is restarted, it includes the new cookie.
6926 {
[email protected]ceefd7fd2012-11-29 00:36:246927 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446928 TestURLRequestContext context(true);
6929 context.set_network_delegate(&network_delegate);
6930 context.Init();
6931
6932 TestDelegate d;
6933 d.set_credentials(AuthCredentials(kUser, kSecret));
6934
davidben151423e2015-03-23 18:48:366935 scoped_ptr<URLRequest> r(
6936 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196937 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446938
[email protected]255620da2013-08-19 13:14:296939 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446940
6941 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6942
6943 // Make sure we sent the cookie in the restarted transaction.
6944 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6945 != std::string::npos);
6946 }
6947
6948 // Same test as above, except this time the restart is initiated earlier
6949 // (without user intervention since identity is embedded in the URL).
6950 {
[email protected]ceefd7fd2012-11-29 00:36:246951 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446952 TestURLRequestContext context(true);
6953 context.set_network_delegate(&network_delegate);
6954 context.Init();
6955
6956 TestDelegate d;
6957
6958 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186959 replacements.SetUsernameStr("user2");
6960 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446961 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6962
davidben151423e2015-03-23 18:48:366963 scoped_ptr<URLRequest> r(
6964 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196965 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446966
[email protected]255620da2013-08-19 13:14:296967 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446968
6969 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6970
6971 // Make sure we sent the cookie in the restarted transaction.
6972 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6973 != std::string::npos);
6974 }
6975}
6976
[email protected]58e32bb2013-01-21 18:23:256977// Tests that load timing works as expected with auth and the cache.
6978TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:556979 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:256980
6981 // populate the cache
6982 {
6983 TestDelegate d;
6984 d.set_credentials(AuthCredentials(kUser, kSecret));
6985
[email protected]f7022f32014-08-21 16:32:196986 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556987 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196988 r->Start();
[email protected]58e32bb2013-01-21 18:23:256989
[email protected]255620da2013-08-19 13:14:296990 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256991
6992 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6993
6994 LoadTimingInfo load_timing_info_before_auth;
6995 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6996 &load_timing_info_before_auth));
6997 TestLoadTimingNotReused(load_timing_info_before_auth,
6998 CONNECT_TIMING_HAS_DNS_TIMES);
6999
7000 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197001 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257002 // The test server does not support keep alive sockets, so the second
7003 // request with auth should use a new socket.
7004 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7005 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7006 load_timing_info.socket_log_id);
7007 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7008 load_timing_info.connect_timing.connect_start);
7009 }
7010
[email protected]3b23a222013-05-15 21:33:257011 // Repeat request with end-to-end validation. Since auth-basic results in a
7012 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:257013 // response should be fetched from the cache.
7014 {
7015 TestDelegate d;
7016 d.set_credentials(AuthCredentials(kUser, kSecret));
7017
[email protected]f7022f32014-08-21 16:32:197018 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557019 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197020 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7021 r->Start();
[email protected]58e32bb2013-01-21 18:23:257022
[email protected]255620da2013-08-19 13:14:297023 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257024
7025 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7026
7027 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197028 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:257029
[email protected]3b23a222013-05-15 21:33:257030 // Since there was a request that went over the wire, the load timing
7031 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:257032 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197033 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257034 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:257035 }
7036}
7037
[email protected]316c1e5e2012-09-12 15:17:447038// In this test, we do a POST which the server will 302 redirect.
7039// The subsequent transaction should use GET, and should not send the
7040// Content-Type header.
7041// http://code.google.com/p/chromium/issues/detail?id=843
7042TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:557043 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447044
7045 const char kData[] = "hello world";
7046
7047 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197048 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557049 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY,
7050 &d));
[email protected]f7022f32014-08-21 16:32:197051 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077052 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447053
7054 // Set headers (some of which are specific to the POST).
7055 HttpRequestHeaders headers;
7056 headers.AddHeadersFromString(
7057 "Content-Type: multipart/form-data; "
7058 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
7059 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
7060 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
7061 "Accept-Language: en-US,en\r\n"
7062 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
7063 "Content-Length: 11\r\n"
7064 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:197065 req->SetExtraRequestHeaders(headers);
7066 req->Start();
[email protected]255620da2013-08-19 13:14:297067 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447068
7069 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197070 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447071 EXPECT_EQ("text/html", mime_type);
7072
7073 const std::string& data = d.data_received();
7074
7075 // Check that the post-specific headers were stripped:
7076 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
7077 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
7078 EXPECT_FALSE(ContainsString(data, "Origin:"));
7079
7080 // These extra request headers should not have been stripped.
7081 EXPECT_TRUE(ContainsString(data, "Accept:"));
7082 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
7083 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
7084}
7085
jww5fe460ff2015-03-28 00:22:517086// The following tests check that we handle mutating the request for HTTP
7087// redirects as expected.
7088// See https://crbug.com/56373, https://crbug.com/102130, and
7089// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:447090
7091TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:557092 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447093
tommycli59a63432015-11-06 00:10:557094 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:517095 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557096 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:447097
7098 HTTPRedirectMethodTest(url, "POST", "GET", true);
7099 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7100 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517101
7102 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7103 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7104 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7105 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7106 std::string());
[email protected]316c1e5e2012-09-12 15:17:447107}
7108
7109TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:557110 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447111
tommycli59a63432015-11-06 00:10:557112 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:517113 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557114 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:447115
7116 HTTPRedirectMethodTest(url, "POST", "GET", true);
7117 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7118 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517119
7120 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7121 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7122 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7123 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7124 std::string());
[email protected]316c1e5e2012-09-12 15:17:447125}
7126
7127TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:557128 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447129
tommycli59a63432015-11-06 00:10:557130 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:517131 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557132 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:447133
7134 HTTPRedirectMethodTest(url, "POST", "GET", true);
7135 HTTPRedirectMethodTest(url, "PUT", "GET", true);
7136 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517137
7138 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7139 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7140 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7141 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7142 std::string());
[email protected]316c1e5e2012-09-12 15:17:447143}
7144
7145TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:557146 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447147
tommycli59a63432015-11-06 00:10:557148 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:517149 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557150 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:447151
7152 HTTPRedirectMethodTest(url, "POST", "POST", true);
7153 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7154 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517155
7156 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7157 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7158 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7159 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:447160}
7161
[email protected]0a17aab32014-04-24 03:32:377162TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:557163 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377164
tommycli59a63432015-11-06 00:10:557165 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:517166 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557167 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:377168
7169 HTTPRedirectMethodTest(url, "POST", "POST", true);
7170 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7171 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517172
7173 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7174 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7175 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7176 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:377177}
7178
7179// Make sure that 308 responses without bodies are not treated as redirects.
7180// Certain legacy apis that pre-date the response code expect this behavior
7181// (Like Google Drive).
7182TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:557183 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377184
7185 TestDelegate d;
tommycli59a63432015-11-06 00:10:557186 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:377187
davidben151423e2015-03-23 18:48:367188 scoped_ptr<URLRequest> request(
7189 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:377190
[email protected]f7022f32014-08-21 16:32:197191 request->Start();
[email protected]0a17aab32014-04-24 03:32:377192 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197193 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
7194 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:377195 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197196 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:377197 EXPECT_EQ("This is not a redirect.", d.data_received());
7198}
7199
[email protected]f878230e2014-04-03 15:36:147200TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:557201 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147202
tommycli59a63432015-11-06 00:10:557203 GURL original_url(
7204 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
7205 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:147206
7207 TestDelegate d;
7208 {
davidben151423e2015-03-23 18:48:367209 scoped_ptr<URLRequest> r(
7210 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:147211
[email protected]f7022f32014-08-21 16:32:197212 r->Start();
[email protected]f878230e2014-04-03 15:36:147213 base::RunLoop().Run();
7214
[email protected]f7022f32014-08-21 16:32:197215 EXPECT_EQ(2U, r->url_chain().size());
7216 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7217 EXPECT_EQ(OK, r->status().error());
7218 EXPECT_EQ(original_url, r->original_url());
7219 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:147220 }
7221}
7222
[email protected]cba24642014-08-15 20:49:597223TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557224 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597225
tommycli59a63432015-11-06 00:10:557226 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597227 GURL first_party_url("http://example.com");
7228
7229 TestDelegate d;
7230 {
davidben151423e2015-03-23 18:48:367231 scoped_ptr<URLRequest> r(
7232 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197233 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:597234
[email protected]f7022f32014-08-21 16:32:197235 r->Start();
[email protected]cba24642014-08-15 20:49:597236 base::RunLoop().Run();
7237
[email protected]f7022f32014-08-21 16:32:197238 EXPECT_EQ(2U, r->url_chain().size());
7239 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7240 EXPECT_EQ(OK, r->status().error());
7241 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597242 }
7243}
7244
7245TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557246 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597247
tommycli59a63432015-11-06 00:10:557248 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597249 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:557250 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:597251
7252 TestDelegate d;
7253 {
davidben151423e2015-03-23 18:48:367254 scoped_ptr<URLRequest> r(
7255 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197256 r->set_first_party_for_cookies(original_first_party_url);
7257 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597258 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7259
[email protected]f7022f32014-08-21 16:32:197260 r->Start();
[email protected]cba24642014-08-15 20:49:597261 base::RunLoop().Run();
7262
[email protected]f7022f32014-08-21 16:32:197263 EXPECT_EQ(2U, r->url_chain().size());
7264 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7265 EXPECT_EQ(OK, r->status().error());
7266 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597267 }
7268}
7269
[email protected]316c1e5e2012-09-12 15:17:447270TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:557271 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447272
7273 const char kData[] = "hello world";
7274
7275 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197276 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557277 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197278 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077279 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447280 HttpRequestHeaders headers;
7281 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517282 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197283 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447284
mmenkeed0498b2015-12-08 23:20:427285 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557286 req.get(), &default_network_delegate_,
7287 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427288 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7289 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447290
[email protected]f7022f32014-08-21 16:32:197291 req->Start();
[email protected]255620da2013-08-19 13:14:297292 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197293 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447294}
7295
7296TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:557297 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447298
7299 const char kData[] = "hello world";
7300
7301 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197302 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557303 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197304 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077305 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447306 HttpRequestHeaders headers;
7307 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517308 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197309 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447310
mmenkeed0498b2015-12-08 23:20:427311 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557312 req.get(), &default_network_delegate_,
7313 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097314 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:427315 "Very Good Reason"));
7316 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447317
[email protected]f7022f32014-08-21 16:32:197318 req->Start();
[email protected]255620da2013-08-19 13:14:297319 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197320 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447321 EXPECT_EQ(kData, d.data_received());
7322}
7323
7324// Check that default A-L header is sent.
7325TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557326 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447327
[email protected]8790210c2013-12-02 05:29:537328 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247329 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447330 TestURLRequestContext context(true);
7331 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437332 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447333 context.Init();
7334
7335 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197336 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557337 http_test_server()->GetURL("/echoheader?Accept-Language"),
7338 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197339 req->Start();
[email protected]255620da2013-08-19 13:14:297340 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447341 EXPECT_EQ("en", d.data_received());
7342}
7343
7344// Check that an empty A-L header is not sent. http://crbug.com/77365.
7345TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557346 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447347
[email protected]8790210c2013-12-02 05:29:537348 std::string empty_string; // Avoid most vexing parse on line below.
7349 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247350 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447351 TestURLRequestContext context(true);
7352 context.set_network_delegate(&network_delegate);
7353 context.Init();
7354 // We override the language after initialization because empty entries
7355 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437356 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447357
7358 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197359 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557360 http_test_server()->GetURL("/echoheader?Accept-Language"),
7361 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197362 req->Start();
[email protected]255620da2013-08-19 13:14:297363 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447364 EXPECT_EQ("None", d.data_received());
7365}
7366
7367// Check that if request overrides the A-L header, the default is not appended.
7368// See http://crbug.com/20894
7369TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557370 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447371
7372 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197373 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557374 http_test_server()->GetURL("/echoheader?Accept-Language"),
7375 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447376 HttpRequestHeaders headers;
7377 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197378 req->SetExtraRequestHeaders(headers);
7379 req->Start();
[email protected]255620da2013-08-19 13:14:297380 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447381 EXPECT_EQ(std::string("ru"), d.data_received());
7382}
7383
7384// Check that default A-E header is sent.
7385TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557386 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447387
7388 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197389 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557390 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7391 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447392 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197393 req->SetExtraRequestHeaders(headers);
7394 req->Start();
[email protected]255620da2013-08-19 13:14:297395 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447396 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7397}
7398
7399// Check that if request overrides the A-E header, the default is not appended.
7400// See http://crbug.com/47381
7401TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557402 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447403
7404 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197405 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557406 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7407 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447408 HttpRequestHeaders headers;
7409 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197410 req->SetExtraRequestHeaders(headers);
7411 req->Start();
[email protected]255620da2013-08-19 13:14:297412 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447413 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7414 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7415}
7416
[email protected]84f05432013-03-15 01:00:127417// Check that setting the A-C header sends the proper header.
7418TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:557419 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447420
7421 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197422 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557423 http_test_server()->GetURL("/echoheader?Accept-Charset"),
7424 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447425 HttpRequestHeaders headers;
7426 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197427 req->SetExtraRequestHeaders(headers);
7428 req->Start();
[email protected]255620da2013-08-19 13:14:297429 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447430 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7431}
7432
7433// Check that default User-Agent header is sent.
7434TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:557435 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447436
7437 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197438 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557439 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7440 &d));
[email protected]f7022f32014-08-21 16:32:197441 req->Start();
[email protected]255620da2013-08-19 13:14:297442 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197443 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377444 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447445}
7446
7447// Check that if request overrides the User-Agent header,
7448// the default is not appended.
marqf14fff8d2015-12-02 15:52:297449// TODO(crbug.com/564656) This test is flaky on iOS.
7450#if defined(OS_IOS)
7451#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
7452#else
7453#define MAYBE_OverrideUserAgent OverrideUserAgent
7454#endif
7455TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:557456 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447457
7458 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197459 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557460 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7461 &d));
[email protected]316c1e5e2012-09-12 15:17:447462 HttpRequestHeaders headers;
7463 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197464 req->SetExtraRequestHeaders(headers);
7465 req->Start();
[email protected]255620da2013-08-19 13:14:297466 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357467 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447468}
7469
[email protected]ee4c30d2012-11-07 15:08:437470// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7471// User-Agent header to be sent but does not send the Accept-Language and
7472// Accept-Charset headers.
7473TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:557474 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:437475
[email protected]ceefd7fd2012-11-29 00:36:247476 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437477 TestURLRequestContext context(true);
7478 context.set_network_delegate(&network_delegate);
7479 context.Init();
7480 // We override the HttpUserAgentSettings after initialization because empty
7481 // entries get overridden by Init().
7482 context.set_http_user_agent_settings(NULL);
7483
7484 struct {
7485 const char* request;
7486 const char* expected_response;
tommycli59a63432015-11-06 00:10:557487 } tests[] = {{"/echoheader?Accept-Language", "None"},
7488 {"/echoheader?Accept-Charset", "None"},
7489 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:437490
viettrungluue4a8b882014-10-16 06:17:387491 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437492 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197493 scoped_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557494 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197495 req->Start();
[email protected]255620da2013-08-19 13:14:297496 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437497 EXPECT_EQ(tests[i].expected_response, d.data_received())
7498 << " Request = \"" << tests[i].request << "\"";
7499 }
7500}
7501
[email protected]5033ab82013-03-22 20:17:467502// Make sure that URLRequest passes on its priority updates to
7503// newly-created jobs after the first one.
7504TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:557505 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:467506
7507 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197508 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557509 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197510 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467511
mmenkeed0498b2015-12-08 23:20:427512 scoped_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557513 req.get(), &default_network_delegate_,
7514 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427515 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7516 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:467517
[email protected]f7022f32014-08-21 16:32:197518 req->SetPriority(LOW);
7519 req->Start();
7520 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467521
mmenkeed0498b2015-12-08 23:20:427522 RequestPriority job_priority;
7523 scoped_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
7524 req.get(), &default_network_delegate_, &job_priority));
7525 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:467526
7527 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297528 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:427529 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:467530}
7531
[email protected]80abdad2014-03-15 00:20:547532// Check that creating a network request while entering/exiting suspend mode
7533// fails as it should. This is the only case where an HttpTransactionFactory
7534// does not return an HttpTransaction.
7535TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7536 // Create a new HttpNetworkLayer that thinks it's suspended.
mmenke2281f3762015-11-02 20:38:177537 scoped_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
7538 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547539 network_layer->OnSuspend();
7540
dchengc7eeda422015-12-26 03:56:487541 HttpCache http_cache(std::move(network_layer),
mmenkee65e7af2015-10-13 17:16:427542 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547543
7544 TestURLRequestContext context(true);
7545 context.set_http_transaction_factory(&http_cache);
7546 context.Init();
7547
7548 TestDelegate d;
davidben151423e2015-03-23 18:48:367549 scoped_ptr<URLRequest> req(
7550 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197551 req->Start();
[email protected]80abdad2014-03-15 00:20:547552 base::RunLoop().Run();
7553
7554 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197555 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7556 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547557}
7558
mmenke2281f3762015-11-02 20:38:177559namespace {
[email protected]80abdad2014-03-15 00:20:547560
mmenke2281f3762015-11-02 20:38:177561// HttpTransactionFactory that synchronously fails to create transactions.
7562class FailingHttpTransactionFactory : public HttpTransactionFactory {
7563 public:
7564 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7565 : network_session_(network_session) {}
7566
7567 ~FailingHttpTransactionFactory() override {}
7568
7569 // HttpTransactionFactory methods:
7570 int CreateTransaction(RequestPriority priority,
7571 scoped_ptr<HttpTransaction>* trans) override {
7572 return ERR_FAILED;
7573 }
7574
7575 HttpCache* GetCache() override { return nullptr; }
7576
7577 HttpNetworkSession* GetSession() override { return network_session_; }
7578
7579 private:
7580 HttpNetworkSession* network_session_;
7581
7582 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7583};
7584
7585} // namespace
7586
7587// Check that when a request that fails to create an HttpTransaction can be
7588// cancelled while the failure notification is pending, and doesn't send two
7589// failure notifications.
7590//
7591// This currently only happens when in suspend mode and there's no cache, but
7592// just use a special HttpTransactionFactory, to avoid depending on those
7593// behaviors.
7594TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7595 FailingHttpTransactionFactory http_transaction_factory(
7596 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547597 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177598 context.set_http_transaction_factory(&http_transaction_factory);
7599 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547600 context.Init();
7601
7602 TestDelegate d;
davidben151423e2015-03-23 18:48:367603 scoped_ptr<URLRequest> req(
7604 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177605 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7606 // try to create an HttpNetworkTransaction synchronously on start).
7607 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197608 req->Start();
mmenke2281f3762015-11-02 20:38:177609 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547610 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177611 // Run pending error task, if there is one.
7612 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547613
7614 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177615 EXPECT_EQ(1, d.response_started_count());
7616 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
7617
7618 // NetworkDelegate should see the cancellation, but not the error.
7619 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7620 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547621}
7622
ttuttlec0c828492015-05-15 01:25:557623TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:557624 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557625
7626 TestDelegate d;
tommycli59a63432015-11-06 00:10:557627 GURL test_url(http_test_server()->GetURL("/"));
ttuttlec0c828492015-05-15 01:25:557628 scoped_ptr<URLRequest> req(
7629 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7630
7631 req->Start();
7632 base::RunLoop().Run();
7633
7634 EXPECT_TRUE(req->response_info().network_accessed);
7635}
7636
7637TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:557638 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557639
7640 // Populate the cache.
7641 TestDelegate d;
7642 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557643 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
ttuttlec0c828492015-05-15 01:25:557644 req->Start();
7645 base::RunLoop().Run();
7646
7647 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7648 EXPECT_TRUE(req->response_info().network_accessed);
7649 EXPECT_FALSE(req->response_info().was_cached);
7650
tommycli59a63432015-11-06 00:10:557651 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
ttuttlec0c828492015-05-15 01:25:557652 DEFAULT_PRIORITY, &d);
7653 req->Start();
7654 base::RunLoop().Run();
7655
7656 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7657 EXPECT_FALSE(req->response_info().network_accessed);
7658 EXPECT_TRUE(req->response_info().was_cached);
7659}
7660
7661TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:557662 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557663
7664 TestDelegate d;
tommycli59a63432015-11-06 00:10:557665 GURL test_url(http_test_server()->GetURL("/"));
ttuttlec0c828492015-05-15 01:25:557666 scoped_ptr<URLRequest> req(
7667 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7668 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7669
7670 req->Start();
7671 base::RunLoop().Run();
7672
7673 EXPECT_FALSE(req->response_info().network_accessed);
7674}
7675
bengr1bf8e942014-11-07 01:36:507676class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7677 public:
7678 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7679 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7680 // tests into the factory tests.
7681 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7682 }
7683
7684 void SetUpFactory() override {
7685 interceptor_ = new MockURLRequestInterceptor();
7686 job_factory_.reset(new URLRequestInterceptingJobFactory(
dchengc7eeda422015-12-26 03:56:487687 std::move(job_factory_), make_scoped_ptr(interceptor_)));
bengr1bf8e942014-11-07 01:36:507688 }
7689
7690 MockURLRequestInterceptor* interceptor() const {
7691 return interceptor_;
7692 }
7693
7694 private:
7695 MockURLRequestInterceptor* interceptor_;
7696};
7697
7698TEST_F(URLRequestInterceptorTestHTTP,
7699 NetworkDelegateNotificationOnRedirectIntercept) {
7700 interceptor()->set_intercept_redirect(true);
7701 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7702 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7703
tommycli59a63432015-11-06 00:10:557704 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507705
7706 TestDelegate d;
7707 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557708 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507709 req->Start();
7710 base::RunLoop().Run();
7711
7712 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7713 // Check we got one good response
7714 EXPECT_TRUE(req->status().is_success());
7715 if (req->status().is_success())
7716 EXPECT_EQ(200, req->response_headers()->response_code());
7717
7718 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7719 EXPECT_EQ(1, d.response_started_count());
7720 EXPECT_EQ(0, d.received_redirect_count());
7721
7722 EXPECT_EQ(1, default_network_delegate()->created_requests());
7723 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7724 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7725}
7726
7727TEST_F(URLRequestInterceptorTestHTTP,
7728 NetworkDelegateNotificationOnErrorIntercept) {
7729 // Intercept that error and respond with an OK response.
7730 interceptor()->set_intercept_final_response(true);
7731 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7732 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7733 default_network_delegate()->set_can_be_intercepted_on_error(true);
7734
tommycli59a63432015-11-06 00:10:557735 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507736
7737 TestDelegate d;
7738 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557739 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:367740 &d));
bengr1bf8e942014-11-07 01:36:507741 req->set_method("GET");
7742 req->Start();
7743 base::RunLoop().Run();
7744
7745 EXPECT_TRUE(interceptor()->did_intercept_final());
7746
7747 // Check we received one good response.
7748 EXPECT_TRUE(req->status().is_success());
7749 if (req->status().is_success())
7750 EXPECT_EQ(200, req->response_headers()->response_code());
7751 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7752 EXPECT_EQ(1, d.response_started_count());
7753 EXPECT_EQ(0, d.received_redirect_count());
7754
7755 EXPECT_EQ(1, default_network_delegate()->created_requests());
7756 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7757 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7758}
7759
7760TEST_F(URLRequestInterceptorTestHTTP,
7761 NetworkDelegateNotificationOnResponseIntercept) {
7762 // Intercept that error and respond with an OK response.
7763 interceptor()->set_intercept_final_response(true);
7764
7765 // Intercept with a real URLRequestHttpJob.
7766 interceptor()->set_use_url_request_http_job(true);
7767
tommycli59a63432015-11-06 00:10:557768 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507769
7770 TestDelegate d;
7771 scoped_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557772 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507773 req->set_method("GET");
7774 req->Start();
7775 base::RunLoop().Run();
7776
7777 EXPECT_TRUE(interceptor()->did_intercept_final());
7778
7779 // Check we received one good response.
7780 EXPECT_TRUE(req->status().is_success());
7781 if (req->status().is_success())
7782 EXPECT_EQ(200, req->response_headers()->response_code());
7783 EXPECT_EQ("hello", d.data_received());
7784 EXPECT_EQ(1, d.response_started_count());
7785 EXPECT_EQ(0, d.received_redirect_count());
7786
7787 EXPECT_EQ(1, default_network_delegate()->created_requests());
7788 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7789 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7790}
7791
mkwst0c5eab872014-11-21 14:18:547792class URLRequestTestReferrerPolicy : public URLRequestTest {
7793 public:
7794 URLRequestTestReferrerPolicy() {}
7795
tommycli59a63432015-11-06 00:10:557796 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
7797 origin_server_.reset(new EmbeddedTestServer(type));
7798 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
7799 origin_server_->AddDefaultHandlers(
7800 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7801 } else {
7802 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7803 }
mkwst0c5eab872014-11-21 14:18:547804 ASSERT_TRUE(origin_server_->Start());
7805 }
7806
tommycli59a63432015-11-06 00:10:557807 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
7808 net::EmbeddedTestServer::Type dest_type) {
7809 origin_server_.reset(new EmbeddedTestServer(origin_type));
7810 if (origin_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
tommycli59a63432015-11-06 00:10:557818 destination_server_.reset(new EmbeddedTestServer(dest_type));
7819 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7820 destination_server_->AddDefaultHandlers(
7821 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7822 } else {
7823 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7824 }
mkwst0c5eab872014-11-21 14:18:547825 ASSERT_TRUE(destination_server_->Start());
7826 }
7827
7828 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7829 const GURL& referrer,
7830 const GURL& expected) {
7831 // Create and execute the request: we'll only have a |destination_server_|
7832 // if the origins are meant to be distinct. Otherwise, we'll use the
7833 // |origin_server_| for both endpoints.
7834 GURL destination_url =
tommycli59a63432015-11-06 00:10:557835 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
7836 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:547837 GURL origin_url =
tommycli59a63432015-11-06 00:10:557838 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:547839
7840 TestDelegate d;
7841 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367842 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547843 req->set_referrer_policy(policy);
7844 req->SetReferrer(referrer.spec());
7845 req->Start();
7846 base::RunLoop().Run();
7847
7848 EXPECT_EQ(1, d.response_started_count());
7849 EXPECT_EQ(1, d.received_redirect_count());
7850 EXPECT_EQ(destination_url, req->url());
7851 EXPECT_TRUE(req->status().is_success());
7852 EXPECT_EQ(200, req->response_headers()->response_code());
7853
7854 EXPECT_EQ(expected.spec(), req->referrer());
7855 if (expected.is_empty())
7856 EXPECT_EQ("None", d.data_received());
7857 else
7858 EXPECT_EQ(expected.spec(), d.data_received());
7859 }
7860
tommycli59a63432015-11-06 00:10:557861 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:547862
7863 private:
tommycli59a63432015-11-06 00:10:557864 scoped_ptr<EmbeddedTestServer> origin_server_;
7865 scoped_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:547866};
7867
7868TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:557869 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547870
7871 VerifyReferrerAfterRedirect(
7872 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557873 origin_server()->GetURL("/path/to/file.html"),
7874 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547875
7876 VerifyReferrerAfterRedirect(
7877 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557878 origin_server()->GetURL("/path/to/file.html"),
7879 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547880
7881 VerifyReferrerAfterRedirect(
7882 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557883 origin_server()->GetURL("/path/to/file.html"),
7884 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547885
7886 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557887 origin_server()->GetURL("/path/to/file.html"),
7888 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547889}
7890
tommycli59a63432015-11-06 00:10:557891TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
7892 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
7893 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547894
7895 VerifyReferrerAfterRedirect(
7896 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557897 origin_server()->GetURL("/path/to/file.html"),
7898 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547899
7900 VerifyReferrerAfterRedirect(
7901 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557902 origin_server()->GetURL("/path/to/file.html"),
7903 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547904
7905 VerifyReferrerAfterRedirect(
7906 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557907 origin_server()->GetURL("/path/to/file.html"),
7908 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547909
7910 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557911 origin_server()->GetURL("/path/to/file.html"),
7912 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547913}
7914
7915TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:557916 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547917
7918 VerifyReferrerAfterRedirect(
7919 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557920 origin_server()->GetURL("/path/to/file.html"),
7921 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547922
7923 VerifyReferrerAfterRedirect(
7924 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557925 origin_server()->GetURL("/path/to/file.html"),
7926 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547927
7928 VerifyReferrerAfterRedirect(
7929 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557930 origin_server()->GetURL("/path/to/file.html"),
7931 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547932
7933 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557934 origin_server()->GetURL("/path/to/file.html"),
7935 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547936}
7937
tommycli59a63432015-11-06 00:10:557938TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7939 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
7940 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547941
7942 VerifyReferrerAfterRedirect(
7943 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557944 origin_server()->GetURL("/path/to/file.html"),
7945 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547946
7947 VerifyReferrerAfterRedirect(
7948 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557949 origin_server()->GetURL("/path/to/file.html"),
7950 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547951
7952 VerifyReferrerAfterRedirect(
7953 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557954 origin_server()->GetURL("/path/to/file.html"),
7955 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547956
7957 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557958 origin_server()->GetURL("/path/to/file.html"),
7959 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547960}
7961
tommycli59a63432015-11-06 00:10:557962TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7963 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
7964 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:547965
7966 VerifyReferrerAfterRedirect(
7967 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557968 origin_server()->GetURL("/path/to/file.html"),
7969 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547970
7971 VerifyReferrerAfterRedirect(
7972 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557973 origin_server()->GetURL("/path/to/file.html"),
7974 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547975
7976 VerifyReferrerAfterRedirect(
7977 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557978 origin_server()->GetURL("/path/to/file.html"),
7979 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:547980
7981 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:557982 origin_server()->GetURL("/path/to/file.html"),
7983 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:547984}
7985
tommycli59a63432015-11-06 00:10:557986TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7987 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
7988 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:547989
7990 VerifyReferrerAfterRedirect(
7991 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:557992 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:547993
7994 VerifyReferrerAfterRedirect(
7995 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:557996 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:547997
7998 VerifyReferrerAfterRedirect(
7999 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558000 origin_server()->GetURL("/path/to/file.html"),
8001 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548002
8003 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558004 origin_server()->GetURL("/path/to/file.html"),
8005 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548006}
8007
[email protected]73e0bba2009-02-19 22:57:098008class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:508009 public:
[email protected]ef2bf422012-05-11 03:27:098010 HTTPSRequestTest() : default_context_(true) {
8011 default_context_.set_network_delegate(&default_network_delegate_);
8012 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:508013 }
dcheng67be2b1f2014-10-27 21:47:298014 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:508015
8016 protected:
[email protected]ceefd7fd2012-11-29 00:36:248017 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:098018 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:468019};
8020
[email protected]c044616e2013-02-20 02:01:268021TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:558022 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8023 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228024 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118025 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:468026
[email protected]ea224582008-12-07 20:25:468027 TestDelegate d;
8028 {
[email protected]f7022f32014-08-21 16:32:198029 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558030 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198031 r->Start();
8032 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:468033
[email protected]255620da2013-08-19 13:14:298034 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:468035
8036 EXPECT_EQ(1, d.response_started_count());
8037 EXPECT_FALSE(d.received_data_before_response());
8038 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198039 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:198040 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198041 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198042 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198043 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:468044 }
[email protected]ea224582008-12-07 20:25:468045}
8046
[email protected]5774ada2010-07-15 06:30:548047TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:558048 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8049 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8050 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228051 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118052 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338053
8054 bool err_allowed = true;
8055 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8056 TestDelegate d;
8057 {
8058 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:198059 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558060 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338061
[email protected]f7022f32014-08-21 16:32:198062 r->Start();
8063 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338064
[email protected]255620da2013-08-19 13:14:298065 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338066
8067 EXPECT_EQ(1, d.response_started_count());
8068 EXPECT_FALSE(d.received_data_before_response());
8069 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178070 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338071 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198072 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178073 } else {
[email protected]bacff652009-03-31 17:50:338074 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178075 }
[email protected]bacff652009-03-31 17:50:338076 }
8077 }
8078}
8079
[email protected]5774ada2010-07-15 06:30:548080TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:558081 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8082 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
8083 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228084 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118085 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338086
8087 // Iterate from false to true, just so that we do the opposite of the
8088 // previous test in order to increase test coverage.
8089 bool err_allowed = false;
8090 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8091 TestDelegate d;
8092 {
8093 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:198094 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558095 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338096
[email protected]f7022f32014-08-21 16:32:198097 r->Start();
8098 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338099
[email protected]255620da2013-08-19 13:14:298100 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338101
8102 EXPECT_EQ(1, d.response_started_count());
8103 EXPECT_FALSE(d.received_data_before_response());
8104 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178105 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338106 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198107 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178108 } else {
[email protected]bacff652009-03-31 17:50:338109 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178110 }
[email protected]bacff652009-03-31 17:50:338111 }
8112 }
8113}
[email protected]73e0bba2009-02-19 22:57:098114
tommycli59a63432015-11-06 00:10:558115// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
8116// security state. (see http://crbug.com/550977).
8117#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:448118// This tests that a load of www.google.com with a certificate error sets
8119// the |certificate_errors_are_fatal| flag correctly. This flag will cause
8120// the interstitial to be fatal.
8121TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
tommycli59a63432015-11-06 00:10:558122 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8123 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8124 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448125 ASSERT_TRUE(test_server.Start());
8126
8127 // We require that the URL be www.google.com in order to pick up the
8128 // preloaded HSTS entries in the TransportSecurityState. This means that we
8129 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:248130 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448131
8132 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248133 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448134 TestURLRequestContext context(true);
8135 context.set_network_delegate(&network_delegate);
8136 context.set_host_resolver(&host_resolver);
8137 TransportSecurityState transport_security_state;
8138 context.set_transport_security_state(&transport_security_state);
8139 context.Init();
8140
8141 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198142 scoped_ptr<URLRequest> r(context.CreateRequest(
8143 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368144 test_server.host_port_pair().port())),
8145 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448146
[email protected]f7022f32014-08-21 16:32:198147 r->Start();
8148 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448149
[email protected]255620da2013-08-19 13:14:298150 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448151
8152 EXPECT_EQ(1, d.response_started_count());
8153 EXPECT_FALSE(d.received_data_before_response());
8154 EXPECT_TRUE(d.have_certificate_errors());
8155 EXPECT_TRUE(d.certificate_errors_are_fatal());
8156}
8157
8158// This tests that cached HTTPS page loads do not cause any updates to the
8159// TransportSecurityState.
8160TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
8161 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
8162 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:558163 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8164 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8165 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448166 ASSERT_TRUE(test_server.Start());
8167
[email protected]9e6968d2014-05-07 21:46:268168 // We require that the URL be www.google.com in order to pick up the static
8169 // and dynamic STS and PKP entries in the TransportSecurityState. This means
8170 // that we have to use a MockHostResolver in order to direct www.google.com to
8171 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448172
8173 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248174 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448175 TestURLRequestContext context(true);
8176 context.set_network_delegate(&network_delegate);
8177 context.set_host_resolver(&host_resolver);
8178 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:268179
martijnc0d6b622015-06-30 19:14:408180 TransportSecurityState::STSState static_sts_state;
8181 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268182 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408183 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:448184 context.set_transport_security_state(&transport_security_state);
8185 context.Init();
8186
martijnc0d6b622015-06-30 19:14:408187 TransportSecurityState::STSState dynamic_sts_state;
8188 TransportSecurityState::PKPState dynamic_pkp_state;
8189 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
8190 &dynamic_sts_state));
8191 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
8192 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268193
[email protected]316c1e5e2012-09-12 15:17:448194 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198195 scoped_ptr<URLRequest> r(context.CreateRequest(
8196 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368197 test_server.host_port_pair().port())),
8198 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448199
[email protected]f7022f32014-08-21 16:32:198200 r->Start();
8201 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448202
[email protected]255620da2013-08-19 13:14:298203 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448204
8205 EXPECT_EQ(1, d.response_started_count());
8206 EXPECT_FALSE(d.received_data_before_response());
8207 EXPECT_TRUE(d.have_certificate_errors());
8208 EXPECT_TRUE(d.certificate_errors_are_fatal());
8209
[email protected]9e6968d2014-05-07 21:46:268210 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408211 TransportSecurityState::STSState new_static_sts_state;
8212 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268213 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408214 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8215 TransportSecurityState::STSState new_dynamic_sts_state;
8216 TransportSecurityState::PKPState new_dynamic_pkp_state;
8217 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8218 "www.google.com", &new_dynamic_sts_state));
8219 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8220 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268221
martijnc0d6b622015-06-30 19:14:408222 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8223 EXPECT_EQ(new_static_sts_state.include_subdomains,
8224 static_sts_state.include_subdomains);
8225 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8226 static_pkp_state.include_subdomains);
8227 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.spki_hashes,
8228 static_pkp_state.spki_hashes));
8229 EXPECT_TRUE(FingerprintsEqual(new_static_pkp_state.bad_spki_hashes,
8230 static_pkp_state.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:448231}
8232
[email protected]8ccc69f2012-11-28 19:52:148233// Make sure HSTS preserves a POST request's method and body.
8234TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8235 static const char kData[] = "hello world";
8236
tommycli59a63432015-11-06 00:10:558237 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8238 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228239 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148240 ASSERT_TRUE(test_server.Start());
8241
8242
8243 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8244 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:558245 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:228246 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148247 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148248
8249 // Force https for www.somewhere.com.
8250 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208251 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8252 bool include_subdomains = false;
8253 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8254 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148255
8256 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8257
8258 TestURLRequestContext context(true);
8259 context.set_host_resolver(&host_resolver);
8260 context.set_transport_security_state(&transport_security_state);
8261 context.set_network_delegate(&network_delegate);
8262 context.Init();
8263
8264 TestDelegate d;
8265 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8266 // cause a certificate error. Ignore the error.
8267 d.set_allow_certificate_errors(true);
8268
[email protected]f7022f32014-08-21 16:32:198269 scoped_ptr<URLRequest> req(context.CreateRequest(
8270 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368271 test_server.host_port_pair().port())),
8272 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198273 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078274 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148275
[email protected]f7022f32014-08-21 16:32:198276 req->Start();
[email protected]255620da2013-08-19 13:14:298277 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148278
[email protected]f7022f32014-08-21 16:32:198279 EXPECT_EQ("https", req->url().scheme());
8280 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148281 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408282
8283 LoadTimingInfo load_timing_info;
8284 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8285 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8286 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148287}
8288
rob4e0be1f2014-09-11 23:40:228289// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8290TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8291 static const char kOriginHeaderValue[] = "http://www.example.com";
8292
tommycli59a63432015-11-06 00:10:558293 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8294 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:228295 ASSERT_TRUE(test_server.Start());
8296
8297 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8298 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:558299 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
8300 // default.
rob4e0be1f2014-09-11 23:40:228301 MockHostResolver host_resolver;
8302
8303 TransportSecurityState transport_security_state;
8304 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8305 bool include_subdomains = false;
8306 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8307
8308 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8309
8310 MockCertVerifier cert_verifier;
8311 cert_verifier.set_default_result(OK);
8312
8313 TestURLRequestContext context(true);
8314 context.set_host_resolver(&host_resolver);
8315 context.set_transport_security_state(&transport_security_state);
8316 context.set_network_delegate(&network_delegate);
8317 context.set_cert_verifier(&cert_verifier);
8318 context.Init();
8319
8320 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8321 test_server.host_port_pair().port()));
8322 url::Replacements<char> replacements;
8323 const char kNewScheme[] = "https";
8324 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8325 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8326
8327 TestDelegate d;
8328 // Quit on redirect to allow response header inspection upon redirect.
8329 d.set_quit_on_redirect(true);
8330
davidben151423e2015-03-23 18:48:368331 scoped_ptr<URLRequest> req(
8332 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228333 // Set Origin header to simulate a cross-origin request.
8334 HttpRequestHeaders request_headers;
8335 request_headers.SetHeader("Origin", kOriginHeaderValue);
8336 req->SetExtraRequestHeaders(request_headers);
8337
8338 req->Start();
8339 base::RunLoop().Run();
8340
8341 EXPECT_EQ(1, d.received_redirect_count());
8342
8343 const HttpResponseHeaders* headers = req->response_headers();
8344 std::string redirect_location;
8345 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8346 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8347
8348 std::string received_cors_header;
8349 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8350 &received_cors_header));
8351 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8352}
8353
Adam Ricecb76ac62015-02-20 05:33:258354// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
8355// are performed in net/websockets/websocket_end_to_end_test.cc.
8356TEST(WebSocketURLRequestTest, HSTSApplied) {
8357 TestNetworkDelegate network_delegate;
8358 TransportSecurityState transport_security_state;
8359 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8360 bool include_subdomains = false;
8361 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8362 TestURLRequestContext context(true);
8363 context.set_transport_security_state(&transport_security_state);
8364 context.set_network_delegate(&network_delegate);
8365 context.Init();
8366 GURL ws_url("ws://example.net/echo");
8367 TestDelegate delegate;
8368 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:368369 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:258370 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
8371 EXPECT_TRUE(ws_url.SchemeIs("wss"));
8372}
8373
[email protected]316c1e5e2012-09-12 15:17:448374namespace {
8375
8376class SSLClientAuthTestDelegate : public TestDelegate {
8377 public:
8378 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8379 }
dchengb03027d2014-10-21 12:00:208380 void OnCertificateRequested(URLRequest* request,
8381 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448382 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178383 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448384 }
8385 int on_certificate_requested_count() {
8386 return on_certificate_requested_count_;
8387 }
8388 private:
8389 int on_certificate_requested_count_;
8390};
8391
8392} // namespace
8393
8394// TODO(davidben): Test the rest of the code. Specifically,
8395// - Filtering which certificates to select.
8396// - Sending a certificate back.
8397// - Getting a certificate request in an SSL renegotiation sending the
8398// HTTP request.
8399TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:558400 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8401 net::SSLServerConfig ssl_config;
8402 ssl_config.require_client_cert = true;
8403 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
8404 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228405 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448406 ASSERT_TRUE(test_server.Start());
8407
8408 SSLClientAuthTestDelegate d;
8409 {
[email protected]f7022f32014-08-21 16:32:198410 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558411 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448412
[email protected]f7022f32014-08-21 16:32:198413 r->Start();
8414 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448415
[email protected]255620da2013-08-19 13:14:298416 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448417
8418 EXPECT_EQ(1, d.on_certificate_requested_count());
8419 EXPECT_FALSE(d.received_data_before_response());
8420 EXPECT_EQ(0, d.bytes_received());
8421
8422 // Send no certificate.
8423 // TODO(davidben): Get temporary client cert import (with keys) working on
8424 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:548425 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:448426
[email protected]255620da2013-08-19 13:14:298427 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448428
8429 EXPECT_EQ(1, d.response_started_count());
8430 EXPECT_FALSE(d.received_data_before_response());
8431 EXPECT_NE(0, d.bytes_received());
8432 }
8433}
8434
8435TEST_F(HTTPSRequestTest, ResumeTest) {
8436 // Test that we attempt a session resume when making two connections to the
8437 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228438 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448439 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228440 SpawnedTestServer test_server(
8441 SpawnedTestServer::TYPE_HTTPS,
8442 ssl_options,
8443 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448444 ASSERT_TRUE(test_server.Start());
8445
8446 SSLClientSocket::ClearSessionCache();
8447
8448 {
8449 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198450 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368451 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448452
[email protected]f7022f32014-08-21 16:32:198453 r->Start();
8454 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448455
[email protected]255620da2013-08-19 13:14:298456 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448457
8458 EXPECT_EQ(1, d.response_started_count());
8459 }
8460
8461 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8462 CloseAllConnections();
8463
8464 {
8465 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198466 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368467 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448468
[email protected]f7022f32014-08-21 16:32:198469 r->Start();
8470 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448471
[email protected]255620da2013-08-19 13:14:298472 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448473
8474 // The response will look like;
8475 // insert abc
8476 // lookup abc
8477 // insert xyz
8478 //
8479 // With a newline at the end which makes the split think that there are
8480 // four lines.
8481
8482 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298483 std::vector<std::string> lines = base::SplitString(
8484 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448485 ASSERT_EQ(4u, lines.size()) << d.data_received();
8486
8487 std::string session_id;
8488
8489 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298490 std::vector<std::string> parts = base::SplitString(
8491 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448492 ASSERT_EQ(2u, parts.size());
8493 if (i == 0) {
8494 EXPECT_EQ("insert", parts[0]);
8495 session_id = parts[1];
8496 } else {
8497 EXPECT_EQ("lookup", parts[0]);
8498 EXPECT_EQ(session_id, parts[1]);
8499 }
8500 }
8501 }
8502}
8503
Adam Langley32352ad2014-10-14 22:31:008504// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8505// the result of fetching "ssl-session-cache" from the test server, indicates
8506// that exactly two different sessions were inserted, with no lookups etc.
8507static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298508 std::vector<std::string> lines = base::SplitString(
8509 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008510 ASSERT_EQ(3u, lines.size()) << session_info;
8511
8512 std::string session_id;
8513 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298514 std::vector<std::string> parts = base::SplitString(
8515 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008516 ASSERT_EQ(2u, parts.size());
8517 EXPECT_EQ("insert", parts[0]);
8518 if (i == 0) {
8519 session_id = parts[1];
8520 } else {
8521 EXPECT_NE(session_id, parts[1]);
8522 }
8523 }
8524}
8525
[email protected]316c1e5e2012-09-12 15:17:448526TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8527 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8528 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228529 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448530 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228531 SpawnedTestServer test_server(
8532 SpawnedTestServer::TYPE_HTTPS,
8533 ssl_options,
8534 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448535 ASSERT_TRUE(test_server.Start());
8536
8537 SSLClientSocket::ClearSessionCache();
8538
8539 {
8540 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198541 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368542 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448543
[email protected]f7022f32014-08-21 16:32:198544 r->Start();
8545 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448546
[email protected]255620da2013-08-19 13:14:298547 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448548
8549 EXPECT_EQ(1, d.response_started_count());
8550 }
8551
8552 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8553 HttpNetworkSession::Params params;
8554 params.host_resolver = default_context_.host_resolver();
8555 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118556 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:448557 params.proxy_service = default_context_.proxy_service();
8558 params.ssl_config_service = default_context_.ssl_config_service();
8559 params.http_auth_handler_factory =
8560 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:418561 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:448562 params.http_server_properties = default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:448563
mmenkee65e7af2015-10-13 17:16:428564 HttpNetworkSession network_session(params);
[email protected]cba24642014-08-15 20:49:598565 scoped_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428566 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448567
8568 default_context_.set_http_transaction_factory(cache.get());
8569
8570 {
8571 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198572 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368573 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448574
[email protected]f7022f32014-08-21 16:32:198575 r->Start();
8576 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448577
[email protected]255620da2013-08-19 13:14:298578 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448579
8580 // The response will look like;
8581 // insert abc
8582 // insert xyz
8583 //
8584 // With a newline at the end which makes the split think that there are
8585 // three lines.
8586
8587 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008588 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448589 }
8590}
8591
davidben8ecc3072014-09-03 23:19:098592#if defined(OS_WIN)
8593
8594namespace {
8595
8596bool IsECDSACipherSuite(uint16_t cipher_suite) {
8597 const char* key_exchange;
8598 const char* cipher;
8599 const char* mac;
8600 bool is_aead;
8601 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
8602 return std::string(key_exchange).find("ECDSA") != std::string::npos;
8603}
8604
8605} // namespace
8606
8607// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
8608// verified.
davidben9399c952014-10-07 04:09:118609TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:098610 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
8611 LOG(INFO) << "Skipping test on this version.";
8612 return;
8613 }
8614
tommycli59a63432015-11-06 00:10:558615 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8616 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
davidben8ecc3072014-09-03 23:19:098617 ASSERT_TRUE(test_server.Start());
8618
8619 TestDelegate d;
8620 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558621 test_server.GetURL("/client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:098622 r->Start();
8623 EXPECT_TRUE(r->is_pending());
8624
8625 base::RunLoop().Run();
8626
8627 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298628 std::vector<std::string> lines = base::SplitString(
8629 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
davidben8ecc3072014-09-03 23:19:098630
8631 for (size_t i = 0; i < lines.size(); i++) {
8632 int cipher_suite;
8633 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
8634 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
8635 << "ClientHello advertised " << cipher_suite;
8636 }
8637}
8638
8639#endif // OS_WIN
8640
Adam Langley32352ad2014-10-14 22:31:008641class FallbackTestURLRequestContext : public TestURLRequestContext {
8642 public:
8643 explicit FallbackTestURLRequestContext(bool delay_initialization)
8644 : TestURLRequestContext(delay_initialization) {}
8645
avibf0746c2015-12-09 19:53:148646 void set_fallback_min_version(uint16_t version) {
nharperb7441ef2016-01-25 23:54:148647 TestSSLConfigService* ssl_config_service = new TestSSLConfigService(
8648 true /* check for EV */, false /* online revocation checking */,
8649 false /* require rev. checking for local
8650 anchors */,
8651 false /* token binding enabled */);
Adam Langley32352ad2014-10-14 22:31:008652 ssl_config_service->set_fallback_min_version(version);
8653 set_ssl_config_service(ssl_config_service);
8654 }
8655};
8656
[email protected]48d2b7c52014-06-27 01:16:558657class HTTPSFallbackTest : public testing::Test {
8658 public:
Adam Langley32352ad2014-10-14 22:31:008659 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298660 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558661
8662 protected:
8663 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8664 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008665 context_.Init();
8666 delegate_.set_allow_certificate_errors(true);
8667
[email protected]48d2b7c52014-06-27 01:16:558668 SpawnedTestServer test_server(
8669 SpawnedTestServer::TYPE_HTTPS,
8670 ssl_options,
8671 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8672 ASSERT_TRUE(test_server.Start());
8673
tommycli59a63432015-11-06 00:10:558674 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
8675 &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558676 request_->Start();
8677
8678 base::RunLoop().Run();
8679 }
8680
avibf0746c2015-12-09 19:53:148681 void set_fallback_min_version(uint16_t version) {
Adam Langley32352ad2014-10-14 22:31:008682 context_.set_fallback_min_version(version);
8683 }
8684
[email protected]48d2b7c52014-06-27 01:16:558685 void ExpectConnection(int version) {
8686 EXPECT_EQ(1, delegate_.response_started_count());
8687 EXPECT_NE(0, delegate_.bytes_received());
8688 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8689 request_->ssl_info().connection_status));
8690 EXPECT_TRUE(request_->ssl_info().connection_status &
8691 SSL_CONNECTION_VERSION_FALLBACK);
8692 }
8693
8694 void ExpectFailure(int error) {
8695 EXPECT_EQ(1, delegate_.response_started_count());
8696 EXPECT_FALSE(request_->status().is_success());
8697 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8698 EXPECT_EQ(error, request_->status().error());
8699 }
8700
8701 private:
8702 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008703 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558704 scoped_ptr<URLRequest> request_;
8705};
8706
davidbenb127ca82015-06-15 19:05:428707// Tests the TLS 1.0 fallback doesn't happen.
8708TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558709 SpawnedTestServer::SSLOptions ssl_options(
8710 SpawnedTestServer::SSLOptions::CERT_OK);
8711 ssl_options.tls_intolerant =
8712 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8713
8714 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428715 ExpectFailure(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION);
8716}
8717
8718// Tests the TLS 1.1 fallback.
8719TEST_F(HTTPSFallbackTest, TLSv1_1Fallback) {
davidbenb127ca82015-06-15 19:05:428720 SpawnedTestServer::SSLOptions ssl_options(
8721 SpawnedTestServer::SSLOptions::CERT_OK);
8722 ssl_options.tls_intolerant =
8723 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8724
8725 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8726 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
8727}
8728
8729// Tests that the TLS 1.1 fallback triggers on closed connections.
8730TEST_F(HTTPSFallbackTest, TLSv1_1FallbackClosed) {
davidbenb127ca82015-06-15 19:05:428731 SpawnedTestServer::SSLOptions ssl_options(
8732 SpawnedTestServer::SSLOptions::CERT_OK);
8733 ssl_options.tls_intolerant =
8734 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8735 ssl_options.tls_intolerance_type =
8736 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8737
8738 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8739 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558740}
8741
8742// This test is disabled on Android because the remote test server doesn't cause
8743// a TCP reset.
8744#if !defined(OS_ANDROID)
davidbenb127ca82015-06-15 19:05:428745// Tests fallback to TLS 1.1 on connection reset.
8746TEST_F(HTTPSFallbackTest, TLSv1_1FallbackReset) {
[email protected]48d2b7c52014-06-27 01:16:558747 SpawnedTestServer::SSLOptions ssl_options(
8748 SpawnedTestServer::SSLOptions::CERT_OK);
8749 ssl_options.tls_intolerant =
davidbenb127ca82015-06-15 19:05:428750 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
[email protected]48d2b7c52014-06-27 01:16:558751 ssl_options.tls_intolerance_type =
8752 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8753
8754 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:428755 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:558756}
8757#endif // !OS_ANDROID
8758
[email protected]12833302014-07-02 01:57:318759// Tests that we don't fallback on handshake failure with servers that implement
8760// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558761TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558762 SpawnedTestServer::SSLOptions ssl_options(
8763 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438764 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558765 // a version fallback.
8766 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438767 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558768 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8769 // connections are rejected.
8770 ssl_options.fallback_scsv_enabled = true;
8771
8772 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8773
8774 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8775 // intolerance. If the fallback SCSV is processed when the original error
8776 // that caused the fallback should be returned, which should be
8777 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8778 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8779}
8780
[email protected]12833302014-07-02 01:57:318781// Tests that we don't fallback on connection closed with servers that implement
8782// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318783TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318784 SpawnedTestServer::SSLOptions ssl_options(
8785 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438786 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318787 // a version fallback.
8788 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438789 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318790 ssl_options.tls_intolerance_type =
8791 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8792 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8793 // connections are rejected.
8794 ssl_options.fallback_scsv_enabled = true;
8795
8796 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8797
8798 // The original error should be replayed on rejected fallback.
8799 ExpectFailure(ERR_CONNECTION_CLOSED);
8800}
8801
davidbenb937d6c2015-05-14 04:53:428802// Test that fallback probe connections don't cause sessions to be cached.
8803TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008804 SpawnedTestServer::SSLOptions ssl_options(
8805 SpawnedTestServer::SSLOptions::CERT_OK);
8806 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428807 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008808 ssl_options.tls_intolerance_type =
8809 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8810 ssl_options.record_resume = true;
8811
8812 SpawnedTestServer test_server(
8813 SpawnedTestServer::TYPE_HTTPS,
8814 ssl_options,
8815 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8816 ASSERT_TRUE(test_server.Start());
8817
8818 SSLClientSocket::ClearSessionCache();
8819
davidbenb937d6c2015-05-14 04:53:428820 // Make a connection that does a probe fallback to TLSv1 but fails because
8821 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008822 // be inserted locally.
8823 {
8824 TestDelegate delegate;
8825 FallbackTestURLRequestContext context(true);
8826
davidbenb937d6c2015-05-14 04:53:428827 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008828 context.Init();
8829 scoped_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558830 test_server.GetURL("/"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008831 request->Start();
8832
8833 base::RunLoop().Run();
8834
8835 EXPECT_EQ(1, delegate.response_started_count());
8836 EXPECT_FALSE(request->status().is_success());
8837 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8838 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8839 request->status().error());
8840 }
8841
davidbenb937d6c2015-05-14 04:53:428842 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008843 {
8844 TestDelegate delegate;
8845 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428846 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008847
8848 context.Init();
davidben151423e2015-03-23 18:48:368849 scoped_ptr<URLRequest> request(context.CreateRequest(
8850 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008851 request->Start();
8852
8853 base::RunLoop().Run();
8854
8855 EXPECT_EQ(1, delegate.response_started_count());
8856 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428857 EXPECT_EQ(
8858 SSL_CONNECTION_VERSION_TLS1,
8859 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008860 EXPECT_TRUE(request->ssl_info().connection_status &
8861 SSL_CONNECTION_VERSION_FALLBACK);
8862
8863 std::vector<std::string> lines;
8864 // If no sessions were cached then the server should have seen two sessions
8865 // inserted with no lookups.
8866 AssertTwoDistinctSessionsInserted(delegate.data_received());
8867 }
8868}
8869
[email protected]a8fed1742013-12-27 02:14:248870class HTTPSSessionTest : public testing::Test {
8871 public:
8872 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598873 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248874
8875 default_context_.set_network_delegate(&default_network_delegate_);
8876 default_context_.set_cert_verifier(&cert_verifier_);
8877 default_context_.Init();
8878 }
dcheng67be2b1f2014-10-27 21:47:298879 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248880
8881 protected:
8882 MockCertVerifier cert_verifier_;
8883 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8884 TestURLRequestContext default_context_;
8885};
8886
8887// Tests that session resumption is not attempted if an invalid certificate
8888// is presented.
8889TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8890 SpawnedTestServer::SSLOptions ssl_options;
8891 ssl_options.record_resume = true;
8892 SpawnedTestServer test_server(
8893 SpawnedTestServer::TYPE_HTTPS,
8894 ssl_options,
8895 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8896 ASSERT_TRUE(test_server.Start());
8897
8898 SSLClientSocket::ClearSessionCache();
8899
8900 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598901 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248902 {
8903 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198904 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368905 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248906
[email protected]f7022f32014-08-21 16:32:198907 r->Start();
8908 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248909
8910 base::RunLoop().Run();
8911
8912 EXPECT_EQ(1, d.response_started_count());
8913 }
8914
8915 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8916 CloseAllConnections();
8917
8918 // Now change the certificate to be acceptable (so that the response is
8919 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598920 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248921 {
8922 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198923 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368924 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248925
[email protected]f7022f32014-08-21 16:32:198926 r->Start();
8927 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248928
8929 base::RunLoop().Run();
8930
8931 // The response will look like;
8932 // insert abc
8933 // insert xyz
8934 //
8935 // With a newline at the end which makes the split think that there are
8936 // three lines.
8937 //
8938 // If a session was presented (eg: a bug), then the response would look
8939 // like;
8940 // insert abc
8941 // lookup abc
8942 // insert xyz
8943
8944 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008945 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248946 }
8947}
8948
[email protected]dffe8242012-03-20 15:14:278949// This the fingerprint of the "Testing CA" certificate used by the testserver.
8950// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268951static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278952 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8953 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8954
[email protected]51523f52013-07-31 21:57:288955// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8956// testserver.
8957static const SHA256HashValue kOCSPTestCertSPKI = { {
8958 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8959 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8960 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8961 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8962} };
8963
[email protected]dffe8242012-03-20 15:14:278964// This is the policy OID contained in the certificates that testserver
8965// generates.
8966static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8967
8968class HTTPSOCSPTest : public HTTPSRequestTest {
8969 public:
8970 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098971 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088972 ev_test_policy_(
8973 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8974 kOCSPTestCertFingerprint,
8975 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028976 }
8977
dcheng67be2b1f2014-10-27 21:47:298978 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098979 SetupContext(&context_);
8980 context_.Init();
[email protected]dffe8242012-03-20 15:14:278981
[email protected]cba24642014-08-15 20:49:598982 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208983 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428984 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508985 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278986
davidben71f35ff2015-04-17 20:54:488987#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098988 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278989 EnsureNSSHttpIOInit();
8990#endif
8991 }
8992
[email protected]ce7d0cbc2013-05-03 18:57:228993 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278994 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538995 // We always overwrite out_cert_status.
8996 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228997 SpawnedTestServer test_server(
8998 SpawnedTestServer::TYPE_HTTPS,
8999 ssl_options,
9000 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:279001 ASSERT_TRUE(test_server.Start());
9002
9003 TestDelegate d;
9004 d.set_allow_certificate_errors(true);
tommycli59a63432015-11-06 00:10:559005 scoped_ptr<URLRequest> r(
9006 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199007 r->Start();
[email protected]dffe8242012-03-20 15:14:279008
[email protected]255620da2013-08-19 13:14:299009 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:279010
9011 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:199012 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:279013 }
9014
dcheng67be2b1f2014-10-27 21:47:299015 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:489016#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279017 ShutdownNSSHttpIO();
9018#endif
9019 }
9020
[email protected]a13234c2012-03-20 21:45:029021 protected:
9022 // SetupContext configures the URLRequestContext that will be used for making
9023 // connetions to testserver. This can be overridden in test subclasses for
9024 // different behaviour.
9025 virtual void SetupContext(URLRequestContext* context) {
nharperb7441ef2016-01-25 23:54:149026 context->set_ssl_config_service(new TestSSLConfigService(
9027 true /* check for EV */, true /* online revocation checking */,
9028 false /* require rev. checking for local
9029 anchors */,
9030 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029031 }
9032
[email protected]dffe8242012-03-20 15:14:279033 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:099034 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:089035 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:279036};
9037
[email protected]a13234c2012-03-20 21:45:029038static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:019039#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:029040 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
9041 // have that ability on other platforms.
9042 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
9043#else
9044 return 0;
9045#endif
9046}
9047
[email protected]3a86a712013-07-30 07:16:209048// SystemSupportsHardFailRevocationChecking returns true iff the current
9049// operating system supports revocation checking and can distinguish between
9050// situations where a given certificate lacks any revocation information (eg:
9051// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
9052// revocation information cannot be obtained (eg: the CRL was unreachable).
9053// If it does not, then tests which rely on 'hard fail' behaviour should be
9054// skipped.
9055static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:489056#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:209057 return true;
9058#else
9059 return false;
9060#endif
9061}
9062
[email protected]a13234c2012-03-20 21:45:029063// SystemUsesChromiumEVMetadata returns true iff the current operating system
9064// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
9065// several tests are effected because our testing EV certificate won't be
9066// recognised as EV.
9067static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:329068#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:579069 // http://crbug.com/117478 - OpenSSL does not support EV validation.
9070 return false;
[email protected]e1b2d732014-03-28 16:20:329071#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
9072 // On OS X and Android, we use the system to tell us whether a certificate is
9073 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:019074 return false;
9075#else
9076 return true;
9077#endif
9078}
9079
[email protected]b6f2de32012-08-17 04:35:089080static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:009081#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:579082 // http://crbug.com/117478 - OpenSSL does not support OCSP.
9083 return false;
9084#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:029085 return base::win::GetVersion() >= base::win::VERSION_VISTA;
9086#elif defined(OS_ANDROID)
9087 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
9088 return false;
9089#else
9090 return true;
9091#endif
9092}
9093
davidbend1fb2f12014-11-08 02:51:009094static bool SystemSupportsOCSPStapling() {
mathpc992e602015-10-21 20:34:039095#if defined(USE_NSS_CERTS) || defined(OS_IOS)
9096 return true;
9097#elif defined(OS_WIN)
9098 return base::win::GetVersion() >= base::win::VERSION_VISTA;
9099#else
9100 return false;
9101#endif
davidbend1fb2f12014-11-08 02:51:009102}
9103
[email protected]dffe8242012-03-20 15:14:279104TEST_F(HTTPSOCSPTest, Valid) {
9105 if (!SystemSupportsOCSP()) {
9106 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9107 return;
9108 }
9109
[email protected]ce7d0cbc2013-05-03 18:57:229110 SpawnedTestServer::SSLOptions ssl_options(
9111 SpawnedTestServer::SSLOptions::CERT_AUTO);
9112 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:279113
[email protected]924e9f92012-12-16 22:00:539114 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129115 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279116
9117 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9118
[email protected]a13234c2012-03-20 21:45:029119 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9120 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:279121
9122 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9123}
9124
9125TEST_F(HTTPSOCSPTest, Revoked) {
9126 if (!SystemSupportsOCSP()) {
9127 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9128 return;
9129 }
9130
[email protected]ce7d0cbc2013-05-03 18:57:229131 SpawnedTestServer::SSLOptions ssl_options(
9132 SpawnedTestServer::SSLOptions::CERT_AUTO);
9133 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:279134
9135 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129136 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279137
[email protected]a592c0432012-12-01 18:10:299138#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:279139 // Doesn't pass on OS X yet for reasons that need to be investigated.
9140 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9141#endif
9142 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9143 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9144}
9145
9146TEST_F(HTTPSOCSPTest, Invalid) {
9147 if (!SystemSupportsOCSP()) {
9148 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9149 return;
9150 }
9151
[email protected]ce7d0cbc2013-05-03 18:57:229152 SpawnedTestServer::SSLOptions ssl_options(
9153 SpawnedTestServer::SSLOptions::CERT_AUTO);
9154 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:279155
[email protected]924e9f92012-12-16 22:00:539156 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129157 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279158
[email protected]a13234c2012-03-20 21:45:029159 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:279160 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279161
9162 // Without a positive OCSP response, we shouldn't show the EV status.
9163 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9164 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9165}
[email protected]a13234c2012-03-20 21:45:029166
davidbend1fb2f12014-11-08 02:51:009167TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:039168 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009169 LOG(WARNING)
9170 << "Skipping test because system doesn't support OCSP stapling";
9171 return;
9172 }
9173
9174 SpawnedTestServer::SSLOptions ssl_options(
9175 SpawnedTestServer::SSLOptions::CERT_AUTO);
9176 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9177 ssl_options.staple_ocsp_response = true;
9178 ssl_options.ocsp_server_unavailable = true;
9179
9180 CertStatus cert_status;
9181 DoConnection(ssl_options, &cert_status);
9182
9183 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9184
9185 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9186 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9187
9188 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9189}
9190
davidben6c3191b2014-11-21 22:38:049191// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489192#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049193#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9194#else
9195#define MAYBE_RevokedStapled RevokedStapled
9196#endif
9197TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
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_REVOKED;
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(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9214 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9215 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9216}
9217
[email protected]3a86a712013-07-30 07:16:209218class HTTPSHardFailTest : public HTTPSOCSPTest {
9219 protected:
dchengb03027d2014-10-21 12:00:209220 void SetupContext(URLRequestContext* context) override {
nharperb7441ef2016-01-25 23:54:149221 context->set_ssl_config_service(new TestSSLConfigService(
9222 false /* check for EV */, false /* online revocation checking */,
9223 true /* require rev. checking for local
9224 anchors */,
9225 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:209226 }
9227};
9228
[email protected]3a86a712013-07-30 07:16:209229TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
9230 if (!SystemSupportsOCSP()) {
9231 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9232 return;
9233 }
9234
9235 if (!SystemSupportsHardFailRevocationChecking()) {
9236 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
9237 << "revocation checking";
9238 return;
9239 }
9240
9241 SpawnedTestServer::SSLOptions ssl_options(
9242 SpawnedTestServer::SSLOptions::CERT_AUTO);
9243 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9244
9245 CertStatus cert_status;
9246 DoConnection(ssl_options, &cert_status);
9247
9248 EXPECT_EQ(CERT_STATUS_REVOKED,
9249 cert_status & CERT_STATUS_REVOKED);
9250
9251 // Without a positive OCSP response, we shouldn't show the EV status.
9252 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9253}
9254
[email protected]a13234c2012-03-20 21:45:029255class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
9256 protected:
dchengb03027d2014-10-21 12:00:209257 void SetupContext(URLRequestContext* context) override {
nharperb7441ef2016-01-25 23:54:149258 context->set_ssl_config_service(new TestSSLConfigService(
9259 true /* check for EV */, false /* online revocation checking */,
9260 false /* require rev. checking for local
9261 anchors */,
9262 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029263 }
9264};
9265
9266TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
9267 if (!SystemSupportsOCSP()) {
9268 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9269 return;
9270 }
9271
[email protected]ce7d0cbc2013-05-03 18:57:229272 SpawnedTestServer::SSLOptions ssl_options(
9273 SpawnedTestServer::SSLOptions::CERT_AUTO);
9274 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029275 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9276
[email protected]924e9f92012-12-16 22:00:539277 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129278 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029279
9280 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9281 cert_status & CERT_STATUS_ALL_ERRORS);
9282
9283 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089284 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9285 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029286}
9287
[email protected]be0fff62013-08-29 23:37:489288TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
9289 if (!SystemSupportsOCSP()) {
9290 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9291 return;
9292 }
9293
9294 SpawnedTestServer::SSLOptions ssl_options(
9295 SpawnedTestServer::SSLOptions::CERT_AUTO);
9296 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9297 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9298
9299 CertStatus cert_status;
9300 DoConnection(ssl_options, &cert_status);
9301
9302 // Currently only works for Windows. When using NSS or OS X, it's not
9303 // possible to determine whether the check failed because of actual
9304 // revocation or because there was an OCSP failure.
9305#if defined(OS_WIN)
9306 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9307#else
9308 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9309#endif
9310
9311 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9312 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9313 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9314}
9315
[email protected]a13234c2012-03-20 21:45:029316TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
9317 if (!SystemSupportsOCSP()) {
9318 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9319 return;
9320 }
9321
[email protected]ce7d0cbc2013-05-03 18:57:229322 SpawnedTestServer::SSLOptions ssl_options(
9323 SpawnedTestServer::SSLOptions::CERT_AUTO);
9324 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:029325 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9326
9327 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129328 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029329
9330 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9331
9332 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9333 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:089334 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9335 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029336}
9337
9338TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
9339 if (!SystemSupportsOCSP()) {
9340 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9341 return;
9342 }
9343
[email protected]ce7d0cbc2013-05-03 18:57:229344 SpawnedTestServer::SSLOptions ssl_options(
9345 SpawnedTestServer::SSLOptions::CERT_AUTO);
9346 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029347 SSLConfigService::SetCRLSet(
9348 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9349
9350 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129351 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029352
9353 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9354 cert_status & CERT_STATUS_ALL_ERRORS);
9355
9356 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089357 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9358 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029359}
9360
[email protected]51523f52013-07-31 21:57:289361TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9362 if (!SystemSupportsOCSP()) {
9363 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9364 return;
9365 }
9366
9367 SpawnedTestServer::SSLOptions ssl_options(
9368 SpawnedTestServer::SSLOptions::CERT_AUTO);
9369 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9370 SSLConfigService::SetCRLSet(
9371 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9372 false, &kOCSPTestCertSPKI, "")));
9373
9374 CertStatus cert_status;
9375 DoConnection(ssl_options, &cert_status);
9376
9377 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9378 // revocation check for EV.
9379 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9380 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9381 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9382 EXPECT_FALSE(
9383 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9384}
9385
9386TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9387 if (!SystemSupportsOCSP()) {
9388 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9389 return;
9390 }
9391
[email protected]ce7d0cbc2013-05-03 18:57:229392 SpawnedTestServer::SSLOptions ssl_options(
9393 SpawnedTestServer::SSLOptions::CERT_AUTO);
9394 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029395 SSLConfigService::SetCRLSet(
9396 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9397
[email protected]51523f52013-07-31 21:57:289398 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129399 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029400
[email protected]51523f52013-07-31 21:57:289401 // Even with a fresh CRLSet, we should still do online revocation checks when
9402 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9403 // test.
9404 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9405 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029406
[email protected]51523f52013-07-31 21:57:289407 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029408 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289409 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029410}
9411
[email protected]b6f2de32012-08-17 04:35:089412TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9413 // Test that when EV verification is requested, but online revocation
9414 // checking is disabled, and the leaf certificate is not in fact EV, that
9415 // no revocation checking actually happens.
9416 if (!SystemSupportsOCSP()) {
9417 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9418 return;
9419 }
9420
9421 // Unmark the certificate's OID as EV, which should disable revocation
9422 // checking (as per the user preference)
9423 ev_test_policy_.reset();
9424
[email protected]ce7d0cbc2013-05-03 18:57:229425 SpawnedTestServer::SSLOptions ssl_options(
9426 SpawnedTestServer::SSLOptions::CERT_AUTO);
9427 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089428 SSLConfigService::SetCRLSet(
9429 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9430
9431 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129432 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:089433
9434 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9435
9436 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9437 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9438}
9439
[email protected]a13234c2012-03-20 21:45:029440class HTTPSCRLSetTest : public HTTPSOCSPTest {
9441 protected:
dchengb03027d2014-10-21 12:00:209442 void SetupContext(URLRequestContext* context) override {
nharperb7441ef2016-01-25 23:54:149443 context->set_ssl_config_service(new TestSSLConfigService(
9444 false /* check for EV */, false /* online revocation checking */,
9445 false /* require rev. checking for local
9446 anchors */,
9447 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029448 }
9449};
9450
9451TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229452 SpawnedTestServer::SSLOptions ssl_options(
9453 SpawnedTestServer::SSLOptions::CERT_AUTO);
9454 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029455 SSLConfigService::SetCRLSet(
9456 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9457
[email protected]924e9f92012-12-16 22:00:539458 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129459 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029460
9461 // If we're not trying EV verification then, even if the CRLSet has expired,
9462 // we don't fall back to online revocation checks.
9463 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9464 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9465 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9466}
[email protected]51523f52013-07-31 21:57:289467
9468TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309469#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289470 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9471 return;
9472#endif
9473
9474 SpawnedTestServer::SSLOptions ssl_options(
9475 SpawnedTestServer::SSLOptions::CERT_AUTO);
9476 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9477 ssl_options.cert_serial = 10;
9478 SSLConfigService::SetCRLSet(
9479 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9480 false, &kOCSPTestCertSPKI, "\x0a")));
9481
9482 CertStatus cert_status = 0;
9483 DoConnection(ssl_options, &cert_status);
9484
9485 // If the certificate is recorded as revoked in the CRLSet, that should be
9486 // reflected without online revocation checking.
9487 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9488 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9489 EXPECT_FALSE(
9490 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9491}
[email protected]316c1e5e2012-09-12 15:17:449492#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279493
mmenke9f2ec60c2015-06-01 20:59:479494#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9495// These tests aren't passing on Android. Either the RemoteTestServer isn't
9496// starting up successfully, or it can't access the test files.
9497// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319498class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119499 public:
[email protected]d9fca99a2012-02-24 16:16:209500 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:479501 : ftp_transaction_factory_(&host_resolver_),
tommycli59a63432015-11-06 00:10:559502 ftp_test_server_(SpawnedTestServer::TYPE_FTP,
9503 SpawnedTestServer::kLocalhost,
9504 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:479505 // Can't use |default_context_|'s HostResolver to set up the
9506 // FTPTransactionFactory because it hasn't been created yet.
9507 default_context_.set_host_resolver(&host_resolver_);
9508 }
9509
9510 // URLRequestTest interface:
9511 void SetUpFactory() override {
9512 // Add FTP support to the default URLRequestContext.
9513 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:209514 "ftp",
9515 make_scoped_ptr(new FtpProtocolHandler(&ftp_transaction_factory_)));
mmenke9f2ec60c2015-06-01 20:59:479516 }
9517
9518 std::string GetTestFileContents() {
9519 base::FilePath path;
9520 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9521 path = path.Append(kTestFilePath);
9522 path = path.AppendASCII(kFtpTestFile);
9523 std::string contents;
9524 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9525 return contents;
[email protected]95409e12010-08-17 20:07:119526 }
9527
[email protected]b89ca032009-08-31 21:41:319528 protected:
mmenke9f2ec60c2015-06-01 20:59:479529 MockHostResolver host_resolver_;
9530 FtpNetworkLayer ftp_transaction_factory_;
9531
tommycli59a63432015-11-06 00:10:559532 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:319533};
9534
[email protected]d2a133182012-08-05 16:44:089535// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099536TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089537 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089538
9539 TestDelegate d;
9540 {
davidben151423e2015-03-23 18:48:369541 scoped_ptr<URLRequest> r(
9542 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199543 r->Start();
9544 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089545
[email protected]255620da2013-08-19 13:14:299546 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089547
[email protected]f7022f32014-08-21 16:32:199548 EXPECT_FALSE(r->is_pending());
9549 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
9550 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:089551 }
9552}
9553
mmenke9f2ec60c2015-06-01 20:59:479554TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:559555 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119556
[email protected]a25e90e2009-09-09 17:05:379557 TestDelegate d;
9558 {
[email protected]f7022f32014-08-21 16:32:199559 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559560 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199561 r->Start();
9562 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379563
[email protected]255620da2013-08-19 13:14:299564 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379565
[email protected]f7022f32014-08-21 16:32:199566 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379567 EXPECT_EQ(1, d.response_started_count());
9568 EXPECT_FALSE(d.received_data_before_response());
9569 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:559570 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199571 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559572 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199573 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379574 }
9575}
9576
mmenke9f2ec60c2015-06-01 20:59:479577TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:559578 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119579
[email protected]dd265012009-01-08 20:45:279580 TestDelegate d;
9581 {
[email protected]f7022f32014-08-21 16:32:199582 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559583 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199584 r->Start();
9585 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279586
[email protected]255620da2013-08-19 13:14:299587 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279588
[email protected]f7022f32014-08-21 16:32:199589 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279590 EXPECT_EQ(1, d.response_started_count());
9591 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479592 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559593 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199594 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559595 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199596 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279597 }
9598}
9599
mmenke9f2ec60c2015-06-01 20:59:479600TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:559601 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119602
[email protected]dd265012009-01-08 20:45:279603 TestDelegate d;
9604 {
tommycli59a63432015-11-06 00:10:559605 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9606 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9607 "chrome"),
9608 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199609 r->Start();
9610 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279611
[email protected]255620da2013-08-19 13:14:299612 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279613
[email protected]f7022f32014-08-21 16:32:199614 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479615 EXPECT_EQ(1, d.response_started_count());
9616 EXPECT_FALSE(d.received_data_before_response());
9617 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559618 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199619 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559620 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199621 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:259622
9623 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:199624 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:259625 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:279626 }
9627}
9628
mmenke9f2ec60c2015-06-01 20:59:479629TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:559630 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119631
[email protected]dd265012009-01-08 20:45:279632 TestDelegate d;
9633 {
[email protected]f7022f32014-08-21 16:32:199634 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559635 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9636 "wrong_password"),
davidben151423e2015-03-23 18:48:369637 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199638 r->Start();
9639 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279640
[email protected]255620da2013-08-19 13:14:299641 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279642
[email protected]f7022f32014-08-21 16:32:199643 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279644 EXPECT_EQ(1, d.response_started_count());
9645 EXPECT_FALSE(d.received_data_before_response());
9646 EXPECT_EQ(d.bytes_received(), 0);
9647 }
9648}
9649
mmenke9f2ec60c2015-06-01 20:59:479650TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:559651 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119652
[email protected]8b8a197d2009-08-26 15:57:589653 TestDelegate d;
9654 // Set correct login credentials. The delegate will be asked for them when
9655 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589656 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589657 {
[email protected]f7022f32014-08-21 16:32:199658 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559659 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9660 "wrong_password"),
davidben151423e2015-03-23 18:48:369661 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199662 r->Start();
9663 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589664
[email protected]255620da2013-08-19 13:14:299665 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589666
[email protected]f7022f32014-08-21 16:32:199667 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589668 EXPECT_EQ(1, d.response_started_count());
9669 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479670 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589671 }
9672}
9673
mmenke9f2ec60c2015-06-01 20:59:479674TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:559675 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119676
[email protected]dd265012009-01-08 20:45:279677 TestDelegate d;
9678 {
mmenke9f2ec60c2015-06-01 20:59:479679 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559680 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9681 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479682 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199683 r->Start();
9684 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279685
[email protected]255620da2013-08-19 13:14:299686 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279687
[email protected]f7022f32014-08-21 16:32:199688 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279689 EXPECT_EQ(1, d.response_started_count());
9690 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479691 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279692 }
9693}
[email protected]8b8a197d2009-08-26 15:57:589694
mmenke9f2ec60c2015-06-01 20:59:479695TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:559696 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119697
[email protected]8b8a197d2009-08-26 15:57:589698 TestDelegate d;
9699 // Set correct login credentials. The delegate will be asked for them when
9700 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589701 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589702 {
mmenke9f2ec60c2015-06-01 20:59:479703 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559704 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9705 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479706 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199707 r->Start();
9708 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589709
[email protected]255620da2013-08-19 13:14:299710 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589711
[email protected]f7022f32014-08-21 16:32:199712 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589713 EXPECT_EQ(1, d.response_started_count());
9714 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479715 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589716 }
9717}
[email protected]60a3df52009-09-22 16:13:249718
mmenke9f2ec60c2015-06-01 20:59:479719TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:559720 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119721
[email protected]60a3df52009-09-22 16:13:249722 scoped_ptr<TestDelegate> d(new TestDelegate);
9723 {
9724 // Pass correct login identity in the URL.
tommycli59a63432015-11-06 00:10:559725 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9726 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9727 "chrome"),
9728 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199729 r->Start();
9730 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249731
[email protected]255620da2013-08-19 13:14:299732 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249733
[email protected]f7022f32014-08-21 16:32:199734 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249735 EXPECT_EQ(1, d->response_started_count());
9736 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479737 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249738 }
9739
9740 d.reset(new TestDelegate);
9741 {
9742 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199743 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559744 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199745 r->Start();
9746 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249747
[email protected]255620da2013-08-19 13:14:299748 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249749
[email protected]f7022f32014-08-21 16:32:199750 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249751 EXPECT_EQ(1, d->response_started_count());
9752 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479753 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249754 }
9755}
9756
mmenke9f2ec60c2015-06-01 20:59:479757TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:559758 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119759
[email protected]60a3df52009-09-22 16:13:249760 scoped_ptr<TestDelegate> d(new TestDelegate);
9761 // Set correct login credentials. The delegate will be asked for them when
9762 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589763 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249764 {
[email protected]f7022f32014-08-21 16:32:199765 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559766 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9767 "wrong_password"),
davidben151423e2015-03-23 18:48:369768 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199769 r->Start();
9770 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249771
[email protected]255620da2013-08-19 13:14:299772 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249773
[email protected]f7022f32014-08-21 16:32:199774 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249775 EXPECT_EQ(1, d->response_started_count());
9776 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479777 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249778 }
9779
9780 // Use a new delegate without explicit credentials. The cached ones should be
9781 // used.
9782 d.reset(new TestDelegate);
9783 {
9784 // Don't pass wrong credentials in the URL, they would override valid cached
9785 // ones.
[email protected]f7022f32014-08-21 16:32:199786 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559787 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199788 r->Start();
9789 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249790
[email protected]255620da2013-08-19 13:14:299791 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249792
[email protected]f7022f32014-08-21 16:32:199793 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249794 EXPECT_EQ(1, d->response_started_count());
9795 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479796 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249797 }
9798}
[email protected]316c1e5e2012-09-12 15:17:449799#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519800
ttuttlec0c828492015-05-15 01:25:559801TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9802 TestDelegate d;
9803 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9804 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9805 d.set_quit_on_network_start(true);
9806
9807 EXPECT_FALSE(req->response_info().network_accessed);
9808
9809 req->Start();
9810 base::RunLoop().Run();
9811
9812 EXPECT_EQ(1, d.received_before_network_start_count());
9813 EXPECT_EQ(0, d.response_started_count());
9814 EXPECT_FALSE(req->response_info().network_accessed);
9815
9816 req->ResumeNetworkStart();
9817 base::RunLoop().Run();
9818}
9819
9820TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9821 TestDelegate d;
9822 scoped_ptr<URLRequest> req(
9823 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9824
9825 EXPECT_FALSE(req->response_info().network_accessed);
9826
9827 req->Start();
9828 base::RunLoop().Run();
9829
9830 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9831 EXPECT_FALSE(req->response_info().network_accessed);
9832}
9833
9834TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9835 MockHostResolver host_resolver;
9836 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9837 TestURLRequestContext context(true);
9838 context.set_network_delegate(&network_delegate);
9839 context.set_host_resolver(&host_resolver);
9840 host_resolver.rules()->AddSimulatedFailure("*");
9841 context.Init();
9842
9843 TestDelegate d;
9844 scoped_ptr<URLRequest> req(context.CreateRequest(
9845 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9846
9847 EXPECT_FALSE(req->response_info().network_accessed);
9848
9849 req->Start();
9850 base::RunLoop().Run();
9851 EXPECT_TRUE(req->response_info().network_accessed);
9852}
9853
mmenkeed0498b2015-12-08 23:20:429854// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:229855// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:429856TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:229857 TestDelegate d;
9858 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9859 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
9860
mmenkeed0498b2015-12-08 23:20:429861 scoped_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:229862 req.get(), &default_network_delegate_,
9863 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:429864 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
9865 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:229866
9867 req->Start();
9868 req->Cancel();
alexanderkcd904b52015-07-24 18:57:229869 base::RunLoop().RunUntilIdle();
9870 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
9871 EXPECT_EQ(0, d.received_redirect_count());
9872}
9873
[email protected]7461a402011-03-24 23:19:519874} // namespace net