blob: ed590d6d47d27e8b5fb14392007fa7f6b9998b8e [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
danakj8522a25b2016-04-16 00:17:365#include <memory>
dchengc7eeda422015-12-26 03:56:486#include <utility>
7
mmenkefd9d15c2017-06-29 13:45:548// This must be before Windows headers
[email protected]ea224582008-12-07 20:25:469#include "build/build_config.h"
10
[email protected]9396b252008-09-29 17:29:3811#if defined(OS_WIN)
[email protected]d8eb84242010-09-25 02:25:0612#include <windows.h>
robliaoeb9bfd642017-05-18 17:35:1613#include <objbase.h>
[email protected]aa84a7e2012-03-15 21:29:0614#include <shlobj.h>
[email protected]9396b252008-09-29 17:29:3815#endif
16
tbansalea2fb8c2015-05-22 22:23:0017#include <stdint.h>
18
initial.commit586acc5fe2008-07-26 22:42:5219#include <algorithm>
avibf0746c2015-12-09 19:53:1420#include <limits>
initial.commit586acc5fe2008-07-26 22:42:5221
nharperb7441ef2016-01-25 23:54:1422#include "base/base64url.h"
[email protected]218aa6a12011-09-13 17:38:3823#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5824#include "base/compiler_specific.h"
mmenke9f2ec60c2015-06-01 20:59:4725#include "base/files/file_path.h"
thestigd8df0332014-09-04 06:33:2926#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0727#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2828#include "base/format_macros.h"
estark06e0dac2015-08-07 21:56:0129#include "base/json/json_reader.h"
skyostil4891b25b2015-06-11 11:43:4530#include "base/location.h"
Avi Drissman13fc8932015-12-20 04:40:4631#include "base/macros.h"
avi0d991472017-04-27 07:04:0432#include "base/memory/ptr_util.h"
[email protected]084262c2011-12-01 21:12:4733#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2234#include "base/message_loop/message_loop.h"
initial.commit586acc5fe2008-07-26 22:42:5235#include "base/path_service.h"
mmenkefb18c772015-09-30 22:22:5036#include "base/power_monitor/power_monitor.h"
37#include "base/power_monitor/power_monitor_source.h"
[email protected]255620da2013-08-19 13:14:2938#include "base/run_loop.h"
skyostil4891b25b2015-06-11 11:43:4539#include "base/single_thread_task_runner.h"
[email protected]4dc3ad4f2013-06-11 07:15:5040#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5541#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2242#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2243#include "base/strings/string_util.h"
44#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0545#include "base/strings/utf_string_conversions.h"
tbansalea2fb8c2015-05-22 22:23:0046#include "base/test/histogram_tester.h"
Emily Stark4cfecf072017-08-08 01:05:5147#include "base/test/scoped_feature_list.h"
gabf767595f2016-05-11 18:50:3548#include "base/threading/thread_task_runner_handle.h"
estark06e0dac2015-08-07 21:56:0149#include "base/values.h"
mmenkefd9d15c2017-06-29 13:45:5450#include "build/buildflag.h"
mmenkecbc2b712014-10-09 20:29:0751#include "net/base/chunked_upload_data_stream.h"
tfarina43a416b2016-01-06 21:48:0752#include "net/base/directory_listing.h"
mmenkecbc2b712014-10-09 20:29:0753#include "net/base/elements_upload_data_stream.h"
initial.commit586acc5fe2008-07-26 22:42:5254#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2555#include "net/base/load_timing_info.h"
56#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0657#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5258#include "net/base/net_module.h"
[email protected]2ca01e52013-10-31 22:05:1959#include "net/base/request_priority.h"
zhongyi18ddddd2017-02-03 19:06:3660#include "net/base/test_completion_callback.h"
[email protected]f288ef02012-12-15 20:28:2861#include "net/base/upload_bytes_element_reader.h"
62#include "net/base/upload_data_stream.h"
63#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4464#include "net/base/url_util.h"
rsleevid6de8302016-06-21 01:33:2065#include "net/cert/ct_policy_enforcer.h"
estark1614475f2016-03-10 03:46:4766#include "net/cert/ct_policy_status.h"
rsleevi22cae1672016-12-28 01:53:3667#include "net/cert/do_nothing_ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1168#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2469#include "net/cert/mock_cert_verifier.h"
zhongyi18ddddd2017-02-03 19:06:3670#include "net/cert/multi_log_ct_verifier.h"
eranmdcec9632016-10-10 14:16:1071#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1172#include "net/cert/test_root_certs.h"
eromaned744f32015-04-09 06:35:4973#include "net/cert_net/nss_ocsp.h"
[email protected]aa84a7e2012-03-15 21:29:0674#include "net/cookies/cookie_monster.h"
75#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5276#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5377#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3878#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5279#include "net/http/http_cache.h"
80#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1981#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2582#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2183#include "net/http/http_response_headers.h"
zhongyi18ddddd2017-02-03 19:06:3684#include "net/http/http_server_properties_impl.h"
[email protected]e50efea2014-03-24 18:41:0085#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0086#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1987#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5188#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4689#include "net/log/test_net_log_entry.h"
90#include "net/log/test_net_log_util.h"
brettwa1228ebb2016-10-28 03:51:3491#include "net/net_features.h"
tbansalca83c002016-04-28 20:56:2892#include "net/nqe/external_estimate_provider.h"
tbansal2ecbbc72016-10-06 17:15:4793#include "net/proxy/proxy_server.h"
[email protected]63de95b2008-12-10 04:11:2794#include "net/proxy/proxy_service.h"
zhongyi18ddddd2017-02-03 19:06:3695#include "net/quic/chromium/mock_crypto_client_stream_factory.h"
96#include "net/quic/chromium/quic_server_info.h"
97#include "net/socket/socket_test_util.h"
[email protected]c3456bb2011-12-12 22:22:1998#include "net/socket/ssl_client_socket.h"
nharperb7441ef2016-01-25 23:54:1499#include "net/ssl/channel_id_service.h"
100#include "net/ssl/default_channel_id_store.h"
[email protected]536fd0b2013-03-14 17:41:57101#include "net/ssl/ssl_connection_status_flags.h"
tommycli59a63432015-11-06 00:10:55102#include "net/ssl/ssl_server_config.h"
nharperb7441ef2016-01-25 23:54:14103#include "net/ssl/token_binding.h"
[email protected]6e7845ae2013-03-29 21:48:11104#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:36105#include "net/test/embedded_test_server/embedded_test_server.h"
106#include "net/test/embedded_test_server/http_request.h"
107#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:01108#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:21109#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43110#include "net/test/test_data_directory.h"
mmenkefb18c772015-09-30 22:22:50111#include "net/test/url_request/url_request_failed_job.h"
rhalavatib7bd7c792017-04-27 05:25:16112#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]e0f35c92013-05-08 16:04:34113#include "net/url_request/data_protocol_handler.h"
Julia Tuttlef9b74062017-07-27 14:44:05114#include "net/url_request/network_error_logging_delegate.h"
[email protected]ee4c30d2012-11-07 15:08:43115#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52116#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50117#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14118#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:50119#include "net/url_request/url_request_intercepting_job_factory.h"
120#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49121#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51122#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47123#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44124#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01125#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52126#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15127#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52128
brettwa1228ebb2016-10-28 03:51:34129#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55130#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29131#include "net/url_request/file_protocol_handler.h"
132#include "net/url_request/url_request_file_dir_job.h"
133#endif
134
brettwa1228ebb2016-10-28 03:51:34135#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47136#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29137#include "net/url_request/ftp_protocol_handler.h"
138#endif
139
[email protected]dffe8242012-03-20 15:14:27140#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48141#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56142#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27143#endif
144
mmenkefd9d15c2017-06-29 13:45:54145#if BUILDFLAG(ENABLE_REPORTING)
146#include "net/reporting/reporting_service.h"
147#endif // BUILDFLAG(ENABLE_REPORTING)
148
robpercival214763f2016-07-01 23:27:01149using net::test::IsError;
150using net::test::IsOk;
151
[email protected]ad65a3e2013-12-25 18:18:01152using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33153using base::Time;
halton.huoe4e45742014-12-08 07:55:46154using std::string;
[email protected]e1acf6f2008-10-27 20:43:33155
[email protected]7461a402011-03-24 23:19:51156namespace net {
157
initial.commit586acc5fe2008-07-26 22:42:52158namespace {
159
xunjieli815ad5b2017-07-18 15:51:35160namespace test0 {
161#include "net/http/transport_security_state_static_unittest0.h"
162}
163
[email protected]42cba2fb2013-03-29 19:58:57164const base::string16 kChrome(ASCIIToUTF16("chrome"));
165const base::string16 kSecret(ASCIIToUTF16("secret"));
166const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44167
mmenke9f2ec60c2015-06-01 20:59:47168const base::FilePath::CharType kTestFilePath[] =
169 FILE_PATH_LITERAL("net/data/url_request_unittest");
170
brettwa1228ebb2016-10-28 03:51:34171#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47172// Test file used in most FTP tests.
173const char kFtpTestFile[] = "BullRunSpeech.txt";
174#endif
175
[email protected]2bba3252013-04-08 19:50:59176// Tests load timing information in the case a fresh connection was used, with
177// no proxy.
[email protected]cba24642014-08-15 20:49:59178void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25179 int connect_timing_flags) {
180 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19181 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25182
183 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
184 EXPECT_FALSE(load_timing_info.request_start.is_null());
185
186 EXPECT_LE(load_timing_info.request_start,
187 load_timing_info.connect_timing.connect_start);
188 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
189 connect_timing_flags);
190 EXPECT_LE(load_timing_info.connect_timing.connect_end,
191 load_timing_info.send_start);
192 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
193 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
194
[email protected]58e32bb2013-01-21 18:23:25195 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
196 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
197}
198
[email protected]2bba3252013-04-08 19:50:59199// Same as above, but with proxy times.
200void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59201 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59202 int connect_timing_flags) {
203 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19204 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59205
206 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
207 EXPECT_FALSE(load_timing_info.request_start.is_null());
208
209 EXPECT_LE(load_timing_info.request_start,
210 load_timing_info.proxy_resolve_start);
211 EXPECT_LE(load_timing_info.proxy_resolve_start,
212 load_timing_info.proxy_resolve_end);
213 EXPECT_LE(load_timing_info.proxy_resolve_end,
214 load_timing_info.connect_timing.connect_start);
215 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
216 connect_timing_flags);
217 EXPECT_LE(load_timing_info.connect_timing.connect_end,
218 load_timing_info.send_start);
219 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
220 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
221}
222
223// Same as above, but with a reused socket and proxy times.
224void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59225 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59226 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19227 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59228
229 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
230 EXPECT_FALSE(load_timing_info.request_start.is_null());
231
232 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
233
234 EXPECT_LE(load_timing_info.request_start,
235 load_timing_info.proxy_resolve_start);
236 EXPECT_LE(load_timing_info.proxy_resolve_start,
237 load_timing_info.proxy_resolve_end);
238 EXPECT_LE(load_timing_info.proxy_resolve_end,
239 load_timing_info.send_start);
240 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
241 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
242}
243
brettwa1228ebb2016-10-28 03:51:34244#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25245// Tests load timing information in the case of a cache hit, when no cache
246// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17247base::StringPiece TestNetResourceProvider(int key) {
248 return "header";
249}
250
251void FillBuffer(char* buffer, size_t len) {
252 static bool called = false;
253 if (!called) {
254 called = true;
255 int seed = static_cast<int>(Time::Now().ToInternalValue());
256 srand(seed);
257 }
258
259 for (size_t i = 0; i < len; i++) {
260 buffer[i] = static_cast<char>(rand());
261 if (!buffer[i])
262 buffer[i] = 'g';
263 }
264}
xunjielia6888202015-04-14 21:34:25265#endif
[email protected]e3a85452013-11-14 01:46:17266
[email protected]3b23a222013-05-15 21:33:25267void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59268 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25269 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19270 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25271
272 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
273 EXPECT_FALSE(load_timing_info.request_start.is_null());
274
275 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
276 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
277 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
278 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
279
280 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
281 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
282}
283
brettwa1228ebb2016-10-28 03:51:34284#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25285// Tests load timing in the case that there is no HTTP response. This can be
286// used to test in the case of errors or non-HTTP requests.
287void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59288 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25289 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19290 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25291
292 // Only the request times should be non-null.
293 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
294 EXPECT_FALSE(load_timing_info.request_start.is_null());
295
296 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
297
298 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
299 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
300 EXPECT_TRUE(load_timing_info.send_start.is_null());
301 EXPECT_TRUE(load_timing_info.send_end.is_null());
302 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
303}
xunjielia6888202015-04-14 21:34:25304#endif
[email protected]58e32bb2013-01-21 18:23:25305
mmenkefb18c772015-09-30 22:22:50306// Test power monitor source that can simulate entering suspend mode. Can't use
307// the one in base/ because it insists on bringing its own MessageLoop.
308class TestPowerMonitorSource : public base::PowerMonitorSource {
309 public:
310 TestPowerMonitorSource() {}
311 ~TestPowerMonitorSource() override {}
312
313 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
314
315 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
316
317 bool IsOnBatteryPowerImpl() override { return false; }
318
319 private:
320 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
321};
322
mmenkeed0498b2015-12-08 23:20:42323// Job that allows monitoring of its priority.
324class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
325 public:
326 // The latest priority of the job is always written to |request_priority_|.
327 PriorityMonitoringURLRequestJob(URLRequest* request,
328 NetworkDelegate* network_delegate,
329 RequestPriority* request_priority)
330 : URLRequestTestJob(request, network_delegate),
331 request_priority_(request_priority) {
332 *request_priority_ = DEFAULT_PRIORITY;
333 }
334
335 void SetPriority(RequestPriority priority) override {
336 *request_priority_ = priority;
337 URLRequestTestJob::SetPriority(priority);
338 }
339
340 private:
341 RequestPriority* const request_priority_;
342};
343
[email protected]71c64f62008-11-15 04:36:51344// Do a case-insensitive search through |haystack| for |needle|.
345bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50346 std::string::const_iterator it = std::search(
347 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
348 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51349 return it != haystack.end();
350}
351
danakj8522a25b2016-04-16 00:17:36352std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
353 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28354 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48355 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23356}
357
[email protected]96adadb2010-08-28 01:16:17358// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51359void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17360 // -1 means unknown. 0 means no encryption.
361 EXPECT_GT(ssl_info.security_bits, 0);
362
363 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14364 uint16_t cipher_suite =
365 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29366 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17367}
368
[email protected]79e1fd62013-06-20 06:50:04369void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
370 const GURL& host_url) {
371 std::string sent_value;
372
373 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
374 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
375
376 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
377 EXPECT_EQ("keep-alive", sent_value);
378}
379
[email protected]dc5a5cf2012-09-26 02:49:30380// A network delegate that allows the user to choose a subset of request stages
381// to block in. When blocking, the delegate can do one of the following:
382// * synchronously return a pre-specified error code, or
383// * asynchronously return that value via an automatically called callback,
384// or
385// * block and wait for the user to do a callback.
386// Additionally, the user may also specify a redirect URL -- then each request
387// with the current URL different from the redirect target will be redirected
388// to that target, in the on-before-URL-request stage, independent of whether
389// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12390class BlockingNetworkDelegate : public TestNetworkDelegate {
391 public:
[email protected]dc5a5cf2012-09-26 02:49:30392 // Stages in which the delegate can block.
393 enum Stage {
[email protected]9045b8822012-01-13 20:35:35394 NOT_BLOCKED = 0,
395 ON_BEFORE_URL_REQUEST = 1 << 0,
396 ON_BEFORE_SEND_HEADERS = 1 << 1,
397 ON_HEADERS_RECEIVED = 1 << 2,
398 ON_AUTH_REQUIRED = 1 << 3
399 };
400
[email protected]dc5a5cf2012-09-26 02:49:30401 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59402 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30403 enum BlockMode {
404 SYNCHRONOUS, // No callback, returns specified return values.
405 AUTO_CALLBACK, // |this| posts a task to run the callback using the
406 // specified return codes.
407 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
408 // |auth_retval_| are ignored. In every blocking stage the
409 // message loop is quit.
rdsmithbf8c3c12016-11-18 18:16:24410 USER_NOTIFY, // User is notified by a provided callback of the
411 // blocking, and synchronously returns instructions
412 // for handling it.
[email protected]dc5a5cf2012-09-26 02:49:30413 };
414
rdsmithbf8c3c12016-11-18 18:16:24415 using NotificationCallback =
416 base::Callback<Error(const CompletionCallback&, const URLRequest*)>;
417
418 using NotificationAuthCallback =
419 base::Callback<NetworkDelegate::AuthRequiredResponse(const AuthCallback&,
420 const URLRequest*)>;
421
[email protected]dc5a5cf2012-09-26 02:49:30422 // Creates a delegate which does not block at all.
423 explicit BlockingNetworkDelegate(BlockMode block_mode);
424
425 // For users to trigger a callback returning |response|.
426 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
427 // Only call if |block_mode_| == USER_CALLBACK.
428 void DoCallback(int response);
429 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
430
431 // Setters.
432 void set_retval(int retval) {
433 ASSERT_NE(USER_CALLBACK, block_mode_);
434 ASSERT_NE(ERR_IO_PENDING, retval);
435 ASSERT_NE(OK, retval);
436 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35437 }
438
[email protected]dc5a5cf2012-09-26 02:49:30439 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
440 // |auth_credentials_| will be passed with the response.
441 void set_auth_retval(AuthRequiredResponse auth_retval) {
442 ASSERT_NE(USER_CALLBACK, block_mode_);
443 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
444 auth_retval_ = auth_retval;
445 }
446 void set_auth_credentials(const AuthCredentials& auth_credentials) {
447 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35448 }
449
[email protected]dc5a5cf2012-09-26 02:49:30450 void set_redirect_url(const GURL& url) {
451 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35452 }
453
[email protected]dc5a5cf2012-09-26 02:49:30454 void set_block_on(int block_on) {
455 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35456 }
457
rdsmithbf8c3c12016-11-18 18:16:24458 // Only valid if |block_mode_| == USER_NOTIFY
459 void set_notification_callback(
460 const NotificationCallback& notification_callback) {
461 notification_callback_ = notification_callback;
462 }
463
464 void set_notification_auth_callback(
465 const NotificationAuthCallback& notification_auth_callback) {
466 notification_auth_callback_ = notification_auth_callback;
467 }
468
[email protected]dc5a5cf2012-09-26 02:49:30469 // Allows the user to check in which state did we block.
470 Stage stage_blocked_for_callback() const {
471 EXPECT_EQ(USER_CALLBACK, block_mode_);
472 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35473 }
474
475 private:
[email protected]dc5a5cf2012-09-26 02:49:30476 void RunCallback(int response, const CompletionCallback& callback);
477 void RunAuthCallback(AuthRequiredResponse response,
478 const AuthCallback& callback);
479
[email protected]9045b8822012-01-13 20:35:35480 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20481 int OnBeforeURLRequest(URLRequest* request,
482 const CompletionCallback& callback,
483 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35484
ryansturm2343cb62016-06-15 01:09:00485 int OnBeforeStartTransaction(URLRequest* request,
486 const CompletionCallback& callback,
487 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35488
dchengb03027d2014-10-21 12:00:20489 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35490 URLRequest* request,
491 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32492 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16493 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13494 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35495
dchengb03027d2014-10-21 12:00:20496 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35497 URLRequest* request,
498 const AuthChallengeInfo& auth_info,
499 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13500 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35501
[email protected]dc5a5cf2012-09-26 02:49:30502 // Resets the callbacks and |stage_blocked_for_callback_|.
503 void Reset();
[email protected]9045b8822012-01-13 20:35:35504
[email protected]dc5a5cf2012-09-26 02:49:30505 // Checks whether we should block in |stage|. If yes, returns an error code
506 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
rdsmithbf8c3c12016-11-18 18:16:24507 int MaybeBlockStage(Stage stage,
508 const URLRequest* request,
509 const CompletionCallback& callback);
[email protected]dc5a5cf2012-09-26 02:49:30510
511 // Configuration parameters, can be adjusted by public methods:
512 const BlockMode block_mode_;
513
514 // Values returned on blocking stages when mode is SYNCHRONOUS or
515 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
516 int retval_; // To be returned in non-auth stages.
517 AuthRequiredResponse auth_retval_;
518
[email protected]5f714132014-03-26 10:41:16519 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30520 int block_on_; // Bit mask: in which stages to block.
521
522 // |auth_credentials_| will be copied to |*target_auth_credential_| on
523 // callback.
524 AuthCredentials auth_credentials_;
525 AuthCredentials* target_auth_credentials_;
526
527 // Internal variables, not set by not the user:
528 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
529 // USER_CALLBACK).
530 Stage stage_blocked_for_callback_;
531
532 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35533 CompletionCallback callback_;
534 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30535
rdsmithbf8c3c12016-11-18 18:16:24536 // Callback to request user instructions for blocking.
537 NotificationCallback notification_callback_;
538 NotificationAuthCallback notification_auth_callback_;
539
[email protected]dc5a5cf2012-09-26 02:49:30540 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
541
542 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35543};
544
[email protected]dc5a5cf2012-09-26 02:49:30545BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
546 : block_mode_(block_mode),
547 retval_(OK),
548 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
549 block_on_(0),
550 target_auth_credentials_(NULL),
551 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32552 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30553}
554
555void BlockingNetworkDelegate::DoCallback(int response) {
556 ASSERT_EQ(USER_CALLBACK, block_mode_);
557 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
558 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
559 CompletionCallback callback = callback_;
560 Reset();
561 RunCallback(response, callback);
562}
563
564void BlockingNetworkDelegate::DoAuthCallback(
565 NetworkDelegate::AuthRequiredResponse response) {
566 ASSERT_EQ(USER_CALLBACK, block_mode_);
567 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
568 AuthCallback auth_callback = auth_callback_;
569 Reset();
570 RunAuthCallback(response, auth_callback);
571}
572
573void BlockingNetworkDelegate::RunCallback(int response,
574 const CompletionCallback& callback) {
575 callback.Run(response);
576}
577
578void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
579 const AuthCallback& callback) {
580 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
581 ASSERT_TRUE(target_auth_credentials_ != NULL);
582 *target_auth_credentials_ = auth_credentials_;
583 }
584 callback.Run(response);
585}
586
587int BlockingNetworkDelegate::OnBeforeURLRequest(
588 URLRequest* request,
589 const CompletionCallback& callback,
590 GURL* new_url) {
591 if (redirect_url_ == request->url())
592 return OK; // We've already seen this request and redirected elsewhere.
593
594 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
595
596 if (!redirect_url_.is_empty())
597 *new_url = redirect_url_;
598
rdsmithbf8c3c12016-11-18 18:16:24599 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30600}
601
ryansturm2343cb62016-06-15 01:09:00602int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30603 URLRequest* request,
604 const CompletionCallback& callback,
605 HttpRequestHeaders* headers) {
ryansturm2343cb62016-06-15 01:09:00606 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]dc5a5cf2012-09-26 02:49:30607
rdsmithbf8c3c12016-11-18 18:16:24608 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30609}
610
611int BlockingNetworkDelegate::OnHeadersReceived(
612 URLRequest* request,
613 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32614 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16615 scoped_refptr<HttpResponseHeaders>* override_response_headers,
616 GURL* allowed_unsafe_redirect_url) {
617 TestNetworkDelegate::OnHeadersReceived(request,
618 callback,
619 original_response_headers,
620 override_response_headers,
621 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30622
rdsmithbf8c3c12016-11-18 18:16:24623 return MaybeBlockStage(ON_HEADERS_RECEIVED, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30624}
625
626NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
627 URLRequest* request,
628 const AuthChallengeInfo& auth_info,
629 const AuthCallback& callback,
630 AuthCredentials* credentials) {
631 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
632 credentials);
633 // Check that the user has provided callback for the previous blocked stage.
634 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
635
636 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
637 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
638 }
639
640 target_auth_credentials_ = credentials;
641
642 switch (block_mode_) {
643 case SYNCHRONOUS:
644 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
645 *target_auth_credentials_ = auth_credentials_;
646 return auth_retval_;
647
648 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45649 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30650 FROM_HERE,
651 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
652 weak_factory_.GetWeakPtr(), auth_retval_, callback));
653 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
654
655 case USER_CALLBACK:
656 auth_callback_ = callback;
657 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45658 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17659 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30660 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
rdsmithbf8c3c12016-11-18 18:16:24661
662 case USER_NOTIFY:
663 // If the callback returns ERR_IO_PENDING, the user has accepted
664 // responsibility for running the callback in the future.
665 return notification_auth_callback_.Run(callback, request);
[email protected]dc5a5cf2012-09-26 02:49:30666 }
667 NOTREACHED();
668 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
669}
670
671void BlockingNetworkDelegate::Reset() {
672 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
673 stage_blocked_for_callback_ = NOT_BLOCKED;
674 callback_.Reset();
675 auth_callback_.Reset();
676}
677
678int BlockingNetworkDelegate::MaybeBlockStage(
679 BlockingNetworkDelegate::Stage stage,
rdsmithbf8c3c12016-11-18 18:16:24680 const URLRequest* request,
[email protected]dc5a5cf2012-09-26 02:49:30681 const CompletionCallback& callback) {
682 // Check that the user has provided callback for the previous blocked stage.
683 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
684
685 if ((block_on_ & stage) == 0) {
686 return OK;
687 }
688
689 switch (block_mode_) {
690 case SYNCHRONOUS:
691 EXPECT_NE(OK, retval_);
692 return retval_;
693
694 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45695 base::ThreadTaskRunnerHandle::Get()->PostTask(
696 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
697 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30698 return ERR_IO_PENDING;
699
700 case USER_CALLBACK:
701 callback_ = callback;
702 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45703 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17704 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30705 return ERR_IO_PENDING;
rdsmithbf8c3c12016-11-18 18:16:24706
707 case USER_NOTIFY:
708 // If the callback returns ERR_IO_PENDING, the user has accepted
709 // responsibility for running the callback in the future.
710 return notification_callback_.Run(callback, request);
[email protected]dc5a5cf2012-09-26 02:49:30711 }
712 NOTREACHED();
713 return 0;
714}
715
[email protected]d5a4dd62012-05-23 01:41:04716class TestURLRequestContextWithProxy : public TestURLRequestContext {
717 public:
718 // Does not own |delegate|.
719 TestURLRequestContextWithProxy(const std::string& proxy,
720 NetworkDelegate* delegate)
721 : TestURLRequestContext(true) {
722 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
723 set_network_delegate(delegate);
724 Init();
725 }
dchengb03027d2014-10-21 12:00:20726 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04727};
728
stefanocsbd5be5202016-06-10 03:37:55729// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01730// URI and report to be sent.
731class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55732 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01733 public:
734 MockCertificateReportSender() {}
735 ~MockCertificateReportSender() override {}
736
meacer5d4dc5a2017-04-27 20:37:48737 void Send(const GURL& report_uri,
738 base::StringPiece content_type,
739 base::StringPiece report,
740 const base::Callback<void()>& success_callback,
741 const base::Callback<void(const GURL&, int, int)>& error_callback)
742 override {
estark06e0dac2015-08-07 21:56:01743 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44744 report.CopyToString(&latest_report_);
745 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01746 }
estark06e0dac2015-08-07 21:56:01747 const GURL& latest_report_uri() { return latest_report_uri_; }
748 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44749 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01750
751 private:
752 GURL latest_report_uri_;
753 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44754 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01755};
756
estarkcd39c11f2015-10-19 19:46:36757class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
758 public:
759 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
760};
761
dadrian612337a2016-07-20 22:36:58762// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
763// This is needed because after the certificate failure, the URLRequest will
764// retry the connection, and return a partial SSLInfo with a cached cert status.
765// The partial SSLInfo does not have the OCSP information filled out.
766class OCSPErrorTestDelegate : public TestDelegate {
767 public:
768 void OnSSLCertificateError(URLRequest* request,
769 const SSLInfo& ssl_info,
770 bool fatal) override {
771 ssl_info_ = ssl_info;
772 on_ssl_certificate_error_called_ = true;
773 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
774 }
775
776 bool on_ssl_certificate_error_called() {
777 return on_ssl_certificate_error_called_;
778 }
779
780 SSLInfo ssl_info() { return ssl_info_; }
781
782 private:
783 bool on_ssl_certificate_error_called_ = false;
784 SSLInfo ssl_info_;
785};
786
[email protected]d5a4dd62012-05-23 01:41:04787} // namespace
788
[email protected]a592c0432012-12-01 18:10:29789// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48790class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00791 public:
fdorayf33fede2017-05-11 21:18:10792 URLRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:09793 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25794 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50795 job_factory_impl_ = new URLRequestJobFactoryImpl();
796 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50797 }
bengr1bf8e942014-11-07 01:36:50798
dcheng67be2b1f2014-10-27 21:47:29799 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18800 // URLRequestJobs may post clean-up tasks on destruction.
801 base::RunLoop().RunUntilIdle();
802 }
[email protected]87a09a92011-07-14 15:50:50803
dcheng2339883c2014-12-23 00:23:05804 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50805 SetUpFactory();
806 default_context_.set_job_factory(job_factory_.get());
807 default_context_.Init();
808 PlatformTest::SetUp();
809 }
810
811 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20812 job_factory_impl_->SetProtocolHandler(
danakj8522a25b2016-04-16 00:17:36813 "data", base::WrapUnique(new DataProtocolHandler));
brettwa1228ebb2016-10-28 03:51:34814#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50815 job_factory_impl_->SetProtocolHandler(
Jeremy Roman0579ed62017-08-29 15:56:19816 "file", std::make_unique<FileProtocolHandler>(
ricea2deef682016-09-09 08:04:07817 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50818#endif
819 }
820
821 TestNetworkDelegate* default_network_delegate() {
822 return &default_network_delegate_;
823 }
824
825 const TestURLRequestContext& default_context() const {
826 return default_context_;
827 }
828
829
[email protected]3c5ca8c2011-09-29 01:14:51830 // Adds the TestJobInterceptor to the default context.
831 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23832 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20833 job_factory_impl_->SetProtocolHandler("http", nullptr);
834 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36835 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23836 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51837 }
838
[email protected]87a09a92011-07-14 15:50:50839 protected:
vishal.b62985ca92015-04-17 08:45:51840 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24841 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50842 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36843 std::unique_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09844 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48845};
846
satoruxddac0442017-05-29 06:06:18847// This NetworkDelegate is picky about what files are accessible. Only
848// whitelisted files are allowed.
849class CookieBlockingNetworkDelegate : public TestNetworkDelegate {
850 public:
851 CookieBlockingNetworkDelegate(){};
852
853 // Adds |directory| to the access white list.
854 void AddToWhitelist(const base::FilePath& directory) {
855 whitelist_.insert(directory);
856 }
857
858 private:
859 // Returns true if |path| matches the white list.
860 bool OnCanAccessFileInternal(const base::FilePath& path) const {
861 for (const auto& directory : whitelist_) {
862 if (directory == path || directory.IsParent(path))
863 return true;
864 }
865 return false;
866 }
867
868 // Returns true only if both |original_path| and |absolute_path| match the
869 // white list.
870 bool OnCanAccessFile(const URLRequest& request,
871 const base::FilePath& original_path,
872 const base::FilePath& absolute_path) const override {
873 return (OnCanAccessFileInternal(original_path) &&
874 OnCanAccessFileInternal(absolute_path));
875 }
876
877 std::set<base::FilePath> whitelist_;
878
879 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
880};
881
[email protected]316c1e5e2012-09-12 15:17:44882TEST_F(URLRequestTest, AboutBlankTest) {
883 TestDelegate d;
884 {
rhalavatib7bd7c792017-04-27 05:25:16885 std::unique_ptr<URLRequest> r(
886 default_context_.CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
887 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44888
[email protected]f7022f32014-08-21 16:32:19889 r->Start();
890 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44891
[email protected]255620da2013-08-19 13:14:29892 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44893
[email protected]f7022f32014-08-21 16:32:19894 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44895 EXPECT_FALSE(d.received_data_before_response());
896 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19897 EXPECT_EQ("", r->GetSocketAddress().host());
898 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04899
900 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19901 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44902 }
903}
904
905TEST_F(URLRequestTest, DataURLImageTest) {
906 TestDelegate d;
907 {
908 // Use our nice little Chrome logo.
danakj8522a25b2016-04-16 00:17:36909 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
910 GURL("data:image/png;base64,"
911 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
912 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
913 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
914 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
915 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
916 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
917 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
918 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
919 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
920 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
921 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
922 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
923 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
924 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
925 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
926 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
927 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
928 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
929 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16930 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44931
[email protected]f7022f32014-08-21 16:32:19932 r->Start();
933 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44934
[email protected]255620da2013-08-19 13:14:29935 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44936
[email protected]f7022f32014-08-21 16:32:19937 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44938 EXPECT_FALSE(d.received_data_before_response());
939 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19940 EXPECT_EQ("", r->GetSocketAddress().host());
941 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04942
943 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19944 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44945 }
946}
947
brettwa1228ebb2016-10-28 03:51:34948#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44949TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15950 base::FilePath app_path;
kraush5a645822016-04-07 18:35:04951
952#if defined(OS_ANDROID)
953 // Android devices are not guaranteed to be able to read /proc/self/exe
954 // Use /etc/hosts instead
955 app_path = base::FilePath("/etc/hosts");
956#else
[email protected]316c1e5e2012-09-12 15:17:44957 PathService::Get(base::FILE_EXE, &app_path);
kraush5a645822016-04-07 18:35:04958#endif // OS_ANDROID
959
[email protected]316c1e5e2012-09-12 15:17:44960 GURL app_url = FilePathToFileURL(app_path);
961
962 TestDelegate d;
963 {
rhalavatib7bd7c792017-04-27 05:25:16964 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
965 app_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44966
[email protected]f7022f32014-08-21 16:32:19967 r->Start();
968 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44969
[email protected]255620da2013-08-19 13:14:29970 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44971
avibf0746c2015-12-09 19:53:14972 int64_t file_size = -1;
[email protected]56285702013-12-04 18:22:49973 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44974
[email protected]f7022f32014-08-21 16:32:19975 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44976 EXPECT_EQ(1, d.response_started_count());
977 EXPECT_FALSE(d.received_data_before_response());
978 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19979 EXPECT_EQ("", r->GetSocketAddress().host());
980 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04981
982 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19983 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44984 }
985}
986
[email protected]ba40bb762012-12-17 07:11:04987TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15988 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04989 PathService::Get(base::FILE_EXE, &app_path);
990 GURL app_url = FilePathToFileURL(app_path);
991
992 TestDelegate d;
993 {
rhalavatib7bd7c792017-04-27 05:25:16994 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
995 app_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:04996
[email protected]f7022f32014-08-21 16:32:19997 r->Start();
998 EXPECT_TRUE(r->is_pending());
999 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:041000 }
[email protected]79e1fd62013-06-20 06:50:041001 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:041002 // destroyed.
[email protected]255620da2013-08-19 13:14:291003 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:041004}
1005
[email protected]316c1e5e2012-09-12 15:17:441006TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1007 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361008 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441009 FillBuffer(buffer.get(), buffer_size);
1010
[email protected]6cdfd7f2013-02-08 20:40:151011 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:521012 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:441013 GURL temp_url = FilePathToFileURL(temp_path);
lazyboy8df84fc2017-04-12 02:12:481014 EXPECT_EQ(static_cast<int>(buffer_size),
1015 base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:441016
avibf0746c2015-12-09 19:53:141017 int64_t file_size;
[email protected]56285702013-12-04 18:22:491018 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:441019
1020 const size_t first_byte_position = 500;
1021 const size_t last_byte_position = buffer_size - first_byte_position;
1022 const size_t content_length = last_byte_position - first_byte_position + 1;
1023 std::string partial_buffer_string(buffer.get() + first_byte_position,
1024 buffer.get() + last_byte_position + 1);
1025
1026 TestDelegate d;
1027 {
rhalavatib7bd7c792017-04-27 05:25:161028 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1029 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441030
1031 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381032 headers.SetHeader(
1033 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591034 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381035 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191036 r->SetExtraRequestHeaders(headers);
1037 r->Start();
1038 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441039
[email protected]255620da2013-08-19 13:14:291040 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191041 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441042 EXPECT_EQ(1, d.response_started_count());
1043 EXPECT_FALSE(d.received_data_before_response());
1044 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1045 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1046 EXPECT_TRUE(partial_buffer_string == d.data_received());
1047 }
1048
[email protected]dd3aa792013-07-16 19:10:231049 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441050}
1051
1052TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1053 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361054 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441055 FillBuffer(buffer.get(), buffer_size);
1056
[email protected]6cdfd7f2013-02-08 20:40:151057 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:521058 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:441059 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:301060 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:441061
avibf0746c2015-12-09 19:53:141062 int64_t file_size;
[email protected]56285702013-12-04 18:22:491063 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:441064
1065 const size_t first_byte_position = 500;
1066 const size_t last_byte_position = buffer_size - 1;
1067 const size_t content_length = last_byte_position - first_byte_position + 1;
1068 std::string partial_buffer_string(buffer.get() + first_byte_position,
1069 buffer.get() + last_byte_position + 1);
1070
1071 TestDelegate d;
1072 {
rhalavatib7bd7c792017-04-27 05:25:161073 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1074 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441075
1076 HttpRequestHeaders headers;
1077 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591078 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381079 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191080 r->SetExtraRequestHeaders(headers);
1081 r->Start();
1082 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441083
[email protected]255620da2013-08-19 13:14:291084 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191085 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441086 EXPECT_EQ(1, d.response_started_count());
1087 EXPECT_FALSE(d.received_data_before_response());
1088 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1089 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1090 EXPECT_TRUE(partial_buffer_string == d.data_received());
1091 }
1092
[email protected]dd3aa792013-07-16 19:10:231093 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441094}
1095
1096TEST_F(URLRequestTest, FileTestMultipleRanges) {
1097 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361098 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441099 FillBuffer(buffer.get(), buffer_size);
1100
[email protected]6cdfd7f2013-02-08 20:40:151101 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:521102 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:441103 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:301104 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:441105
avibf0746c2015-12-09 19:53:141106 int64_t file_size;
[email protected]56285702013-12-04 18:22:491107 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:441108
1109 TestDelegate d;
1110 {
rhalavatib7bd7c792017-04-27 05:25:161111 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1112 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441113
1114 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381115 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191116 r->SetExtraRequestHeaders(headers);
1117 r->Start();
1118 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441119
[email protected]255620da2013-08-19 13:14:291120 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441121 EXPECT_TRUE(d.request_failed());
1122 }
1123
[email protected]dd3aa792013-07-16 19:10:231124 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441125}
1126
[email protected]3ca8b362013-11-11 22:18:071127TEST_F(URLRequestTest, AllowFileURLs) {
1128 base::ScopedTempDir temp_dir;
1129 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181130 // Get an absolute path since |temp_dir| can contain a symbolic link. As of
1131 // now, Mac and Android bots return a path with a symbolic link.
1132 base::FilePath absolute_temp_dir =
1133 base::MakeAbsoluteFilePath(temp_dir.GetPath());
1134
[email protected]3ca8b362013-11-11 22:18:071135 base::FilePath test_file;
satoruxddac0442017-05-29 06:06:181136 ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, &test_file));
1137 // The directory part of the path returned from CreateTemporaryFileInDir()
1138 // can be slightly different from |absolute_temp_dir| on Windows.
1139 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1140 // Hence the test should use the directory name of |test_file|, rather than
1141 // |absolute_temp_dir|, for whitelisting.
1142 base::FilePath real_temp_dir = test_file.DirName();
[email protected]3ca8b362013-11-11 22:18:071143 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:301144 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:591145 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071146 {
1147 TestDelegate d;
satoruxddac0442017-05-29 06:06:181148 CookieBlockingNetworkDelegate network_delegate;
1149 network_delegate.AddToWhitelist(real_temp_dir);
[email protected]3ca8b362013-11-11 22:18:071150 default_context_.set_network_delegate(&network_delegate);
rhalavatib7bd7c792017-04-27 05:25:161151 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1152 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191153 r->Start();
[email protected]3ca8b362013-11-11 22:18:071154 base::RunLoop().Run();
satoruxddac0442017-05-29 06:06:181155 // This should be allowed as the file path is whitelisted.
[email protected]3ca8b362013-11-11 22:18:071156 EXPECT_FALSE(d.request_failed());
1157 EXPECT_EQ(test_data, d.data_received());
1158 }
1159
1160 {
1161 TestDelegate d;
satoruxddac0442017-05-29 06:06:181162 CookieBlockingNetworkDelegate network_delegate;
[email protected]3ca8b362013-11-11 22:18:071163 default_context_.set_network_delegate(&network_delegate);
rhalavatib7bd7c792017-04-27 05:25:161164 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1165 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191166 r->Start();
[email protected]3ca8b362013-11-11 22:18:071167 base::RunLoop().Run();
satoruxddac0442017-05-29 06:06:181168 // This should be rejected as the file path is not whitelisted.
[email protected]3ca8b362013-11-11 22:18:071169 EXPECT_TRUE(d.request_failed());
1170 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181171 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071172 }
1173}
1174
Kevin Marshalla9f05ec2017-07-14 02:10:051175#if defined(OS_POSIX) && !defined(OS_FUCHSIA) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181176
1177TEST_F(URLRequestTest, SymlinksToFiles) {
1178 base::ScopedTempDir temp_dir;
1179 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1180 // Get an absolute path since temp_dir can contain a symbolic link.
1181 base::FilePath absolute_temp_dir =
1182 base::MakeAbsoluteFilePath(temp_dir.GetPath());
1183
1184 // Create a good directory (will be whitelisted) and a good file.
1185 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1186 ASSERT_TRUE(base::CreateDirectory(good_dir));
1187 base::FilePath good_file;
1188 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1189 std::string good_data("good");
1190 base::WriteFile(good_file, good_data.data(), good_data.size());
1191 // See the comment in AllowFileURLs() for why this is done.
1192 base::FilePath real_good_dir = good_file.DirName();
1193
1194 // Create a bad directory (will not be whitelisted) and a bad file.
1195 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1196 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1197 base::FilePath bad_file;
1198 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1199 std::string bad_data("bad");
1200 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1201
1202 // This symlink will point to the good file. Access to the symlink will be
1203 // allowed as both the symlink and the destination file are in the same
1204 // good directory.
1205 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1206 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1207 GURL good_file_url = FilePathToFileURL(good_symlink);
1208 // This symlink will point to the bad file. Even though the symlink is in
1209 // the good directory, access to the symlink will be rejected since it
1210 // points to the bad file.
1211 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1212 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1213 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1214
1215 CookieBlockingNetworkDelegate network_delegate;
1216 network_delegate.AddToWhitelist(real_good_dir);
1217 {
1218 TestDelegate d;
1219 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371220 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1221 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181222 r->Start();
1223 base::RunLoop().Run();
1224 // good_file_url should be allowed.
1225 EXPECT_FALSE(d.request_failed());
1226 EXPECT_EQ(good_data, d.data_received());
1227 }
1228
1229 {
1230 TestDelegate d;
1231 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371232 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1233 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181234 r->Start();
1235 base::RunLoop().Run();
1236 // bad_file_url should be rejected.
1237 EXPECT_TRUE(d.request_failed());
1238 EXPECT_EQ("", d.data_received());
1239 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1240 }
1241}
1242
1243TEST_F(URLRequestTest, SymlinksToDirs) {
1244 base::ScopedTempDir temp_dir;
1245 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1246 // Get an absolute path since temp_dir can contain a symbolic link.
1247 base::FilePath absolute_temp_dir =
1248 base::MakeAbsoluteFilePath(temp_dir.GetPath());
1249
1250 // Create a good directory (will be whitelisted).
1251 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1252 ASSERT_TRUE(base::CreateDirectory(good_dir));
1253
1254 // Create a bad directory (will not be whitelisted).
1255 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1256 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1257
1258 // This symlink will point to the good directory. Access to the symlink
1259 // will be allowed as the symlink is in the good dir that'll be white
1260 // listed.
1261 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1262 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1263 GURL good_file_url = FilePathToFileURL(good_symlink);
1264 // This symlink will point to the bad directory. Even though the symlink is
1265 // in the good directory, access to the symlink will be rejected since it
1266 // points to the bad directory.
1267 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1268 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1269 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1270
1271 CookieBlockingNetworkDelegate network_delegate;
1272 network_delegate.AddToWhitelist(good_dir);
1273 {
1274 TestDelegate d;
1275 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371276 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1277 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181278 r->Start();
1279 base::RunLoop().Run();
1280 // good_file_url should be allowed.
1281 EXPECT_FALSE(d.request_failed());
1282 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1283 }
1284
1285 {
1286 TestDelegate d;
1287 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371288 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1289 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181290 r->Start();
1291 base::RunLoop().Run();
1292 // bad_file_url should be rejected.
1293 EXPECT_TRUE(d.request_failed());
1294 EXPECT_EQ("", d.data_received());
1295 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1296 }
1297}
1298
Kevin Marshalla9f05ec2017-07-14 02:10:051299#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA)
[email protected]316c1e5e2012-09-12 15:17:441300
1301TEST_F(URLRequestTest, FileDirCancelTest) {
1302 // Put in mock resource provider.
1303 NetModule::SetResourceProvider(TestNetResourceProvider);
1304
1305 TestDelegate d;
1306 {
[email protected]6cdfd7f2013-02-08 20:40:151307 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441308 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1309 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1310 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1311
danakj8522a25b2016-04-16 00:17:361312 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161313 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1314 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191315 req->Start();
1316 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441317
1318 d.set_cancel_in_received_data_pending(true);
1319
[email protected]255620da2013-08-19 13:14:291320 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441321 }
1322
1323 // Take out mock resource provider.
1324 NetModule::SetResourceProvider(NULL);
1325}
1326
[email protected]5f9581402013-10-30 13:08:321327TEST_F(URLRequestTest, FileDirOutputSanity) {
1328 // Verify the general sanity of the the output of the file:
1329 // directory lister by checking for the output of a known existing
1330 // file.
1331 const char sentinel_name[] = "filedir-sentinel";
1332
1333 base::FilePath path;
1334 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471335 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321336
1337 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161338 std::unique_ptr<URLRequest> req(
1339 default_context_.CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1340 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191341 req->Start();
[email protected]5f9581402013-10-30 13:08:321342 base::RunLoop().Run();
1343
1344 // Generate entry for the sentinel file.
1345 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581346 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491347 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321348 EXPECT_GT(info.size, 0);
1349 std::string sentinel_output = GetDirectoryListingEntry(
1350 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181351 std::string(sentinel_name), false /* is_dir */, info.size,
1352
[email protected]5f9581402013-10-30 13:08:321353 info.last_modified);
1354
1355 ASSERT_LT(0, d.bytes_received());
1356 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501357 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321358 // Check for the entry generated for the "sentinel" file.
1359 const std::string& data = d.data_received();
1360 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1361}
1362
[email protected]316c1e5e2012-09-12 15:17:441363TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1364 // There is an implicit redirect when loading a file path that matches a
1365 // directory and does not end with a slash. Ensure that following such
1366 // redirects does not crash. See http://crbug.com/18686.
1367
[email protected]6cdfd7f2013-02-08 20:40:151368 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441369 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471370 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441371
1372 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161373 std::unique_ptr<URLRequest> req(
1374 default_context_.CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1375 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191376 req->Start();
[email protected]255620da2013-08-19 13:14:291377 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441378
1379 ASSERT_EQ(1, d.received_redirect_count());
1380 ASSERT_LT(0, d.bytes_received());
1381 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501382 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441383}
1384
1385#if defined(OS_WIN)
1386// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1387TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1388 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161389 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
1390 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191391 req->Start();
[email protected]255620da2013-08-19 13:14:291392 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441393
1394 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501395 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441396}
[email protected]5ecf7cb282014-05-11 01:49:551397#endif // defined(OS_WIN)
1398
brettwa1228ebb2016-10-28 03:51:341399#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551400
1401TEST_F(URLRequestTest, InvalidUrlTest) {
1402 TestDelegate d;
1403 {
rhalavatib7bd7c792017-04-27 05:25:161404 std::unique_ptr<URLRequest> r(
1405 default_context_.CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1406 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551407
[email protected]f7022f32014-08-21 16:32:191408 r->Start();
1409 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551410
1411 base::RunLoop().Run();
1412 EXPECT_TRUE(d.request_failed());
1413 }
1414}
1415
jochen0e3b3a62014-09-16 18:31:231416TEST_F(URLRequestTest, InvalidReferrerTest) {
1417 TestURLRequestContext context;
1418 TestNetworkDelegate network_delegate;
1419 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1420 context.set_network_delegate(&network_delegate);
1421 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361422 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161423 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1424 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231425 req->SetReferrer("https://somewhere.com/");
1426
1427 req->Start();
1428 base::RunLoop().Run();
1429 EXPECT_TRUE(d.request_failed());
1430}
1431
[email protected]5ecf7cb282014-05-11 01:49:551432#if defined(OS_WIN)
1433TEST_F(URLRequestTest, ResolveShortcutTest) {
1434 base::FilePath app_path;
1435 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471436 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551437 app_path = app_path.AppendASCII("with-headers.html");
1438
1439 std::wstring lnk_path = app_path.value() + L".lnk";
1440
1441 base::win::ScopedCOMInitializer com_initializer;
1442
1443 // Temporarily create a shortcut for test
1444 {
1445 base::win::ScopedComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161446 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
1447 CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
[email protected]5ecf7cb282014-05-11 01:49:551448 base::win::ScopedComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001449 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
[email protected]5ecf7cb282014-05-11 01:49:551450 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1451 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1452 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1453 }
1454
1455 TestDelegate d;
1456 {
danakj8522a25b2016-04-16 00:17:361457 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161458 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1459 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551460
[email protected]f7022f32014-08-21 16:32:191461 r->Start();
1462 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551463
1464 base::RunLoop().Run();
1465
1466 WIN32_FILE_ATTRIBUTE_DATA data;
1467 GetFileAttributesEx(app_path.value().c_str(),
1468 GetFileExInfoStandard, &data);
1469 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1470 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1471 FILE_ATTRIBUTE_NORMAL, NULL);
1472 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361473 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551474 DWORD read_size;
1475 BOOL result;
1476 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1477 &read_size, NULL);
1478 std::string content(buffer.get(), read_size);
1479 CloseHandle(file);
1480
[email protected]f7022f32014-08-21 16:32:191481 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551482 EXPECT_EQ(1, d.received_redirect_count());
1483 EXPECT_EQ(content, d.data_received());
1484 }
1485
1486 // Clean the shortcut
1487 DeleteFile(lnk_path.c_str());
1488}
1489#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441490
1491// Custom URLRequestJobs for use with interceptor tests
1492class RestartTestJob : public URLRequestTestJob {
1493 public:
1494 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1495 : URLRequestTestJob(request, network_delegate, true) {}
1496 protected:
dchengb03027d2014-10-21 12:00:201497 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441498 private:
dchengb03027d2014-10-21 12:00:201499 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441500};
1501
1502class CancelTestJob : public URLRequestTestJob {
1503 public:
1504 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1505 : URLRequestTestJob(request, network_delegate, true) {}
1506 protected:
dchengb03027d2014-10-21 12:00:201507 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441508 private:
dchengb03027d2014-10-21 12:00:201509 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441510};
1511
1512class CancelThenRestartTestJob : public URLRequestTestJob {
1513 public:
1514 explicit CancelThenRestartTestJob(URLRequest* request,
1515 NetworkDelegate* network_delegate)
1516 : URLRequestTestJob(request, network_delegate, true) {
1517 }
1518 protected:
dchengb03027d2014-10-21 12:00:201519 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441520 request_->Cancel();
1521 this->NotifyRestartRequired();
1522 }
1523 private:
dchengb03027d2014-10-21 12:00:201524 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441525};
1526
bengr1bf8e942014-11-07 01:36:501527// An Interceptor for use with interceptor tests.
1528class MockURLRequestInterceptor : public URLRequestInterceptor {
1529 public:
1530 // Static getters for canned response header and data strings.
1531 static std::string ok_data() {
1532 return URLRequestTestJob::test_data_1();
1533 }
1534
1535 static std::string ok_headers() {
1536 return URLRequestTestJob::test_headers();
1537 }
1538
1539 static std::string redirect_data() {
1540 return std::string();
1541 }
1542
1543 static std::string redirect_headers() {
1544 return URLRequestTestJob::test_redirect_headers();
1545 }
1546
1547 static std::string error_data() {
1548 return std::string("ohhh nooooo mr. bill!");
1549 }
1550
1551 static std::string error_headers() {
1552 return URLRequestTestJob::test_error_headers();
1553 }
1554
1555 MockURLRequestInterceptor()
1556 : intercept_main_request_(false), restart_main_request_(false),
1557 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1558 simulate_main_network_error_(false),
1559 intercept_redirect_(false), cancel_redirect_request_(false),
1560 intercept_final_response_(false), cancel_final_request_(false),
1561 use_url_request_http_job_(false),
1562 did_intercept_main_(false), did_restart_main_(false),
1563 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1564 did_simulate_error_main_(false),
1565 did_intercept_redirect_(false), did_cancel_redirect_(false),
1566 did_intercept_final_(false), did_cancel_final_(false) {
1567 }
1568
1569 ~MockURLRequestInterceptor() override {
1570 }
1571
1572 // URLRequestInterceptor implementation:
1573 URLRequestJob* MaybeInterceptRequest(
1574 URLRequest* request,
1575 NetworkDelegate* network_delegate) const override {
1576 if (restart_main_request_) {
1577 restart_main_request_ = false;
1578 did_restart_main_ = true;
1579 return new RestartTestJob(request, network_delegate);
1580 }
1581 if (cancel_main_request_) {
1582 cancel_main_request_ = false;
1583 did_cancel_main_ = true;
1584 return new CancelTestJob(request, network_delegate);
1585 }
1586 if (cancel_then_restart_main_request_) {
1587 cancel_then_restart_main_request_ = false;
1588 did_cancel_then_restart_main_ = true;
1589 return new CancelThenRestartTestJob(request, network_delegate);
1590 }
1591 if (simulate_main_network_error_) {
1592 simulate_main_network_error_ = false;
1593 did_simulate_error_main_ = true;
1594 if (use_url_request_http_job_) {
1595 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1596 }
1597 // This job will result in error since the requested URL is not one of the
1598 // URLs supported by these tests.
1599 return new URLRequestTestJob(request, network_delegate, true);
1600 }
1601 if (!intercept_main_request_)
1602 return nullptr;
1603 intercept_main_request_ = false;
1604 did_intercept_main_ = true;
1605 URLRequestTestJob* job = new URLRequestTestJob(request,
1606 network_delegate,
1607 main_headers_,
1608 main_data_,
1609 true);
1610 job->set_load_timing_info(main_request_load_timing_info_);
1611 return job;
1612 }
1613
1614 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1615 NetworkDelegate* network_delegate,
1616 const GURL& location) const override {
1617 if (cancel_redirect_request_) {
1618 cancel_redirect_request_ = false;
1619 did_cancel_redirect_ = true;
1620 return new CancelTestJob(request, network_delegate);
1621 }
1622 if (!intercept_redirect_)
1623 return nullptr;
1624 intercept_redirect_ = false;
1625 did_intercept_redirect_ = true;
1626 if (use_url_request_http_job_) {
1627 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1628 }
1629 return new URLRequestTestJob(request,
1630 network_delegate,
1631 redirect_headers_,
1632 redirect_data_,
1633 true);
1634 }
1635
1636 URLRequestJob* MaybeInterceptResponse(
1637 URLRequest* request,
1638 NetworkDelegate* network_delegate) const override {
1639 if (cancel_final_request_) {
1640 cancel_final_request_ = false;
1641 did_cancel_final_ = true;
1642 return new CancelTestJob(request, network_delegate);
1643 }
1644 if (!intercept_final_response_)
1645 return nullptr;
1646 intercept_final_response_ = false;
1647 did_intercept_final_ = true;
1648 if (use_url_request_http_job_) {
1649 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1650 }
1651 return new URLRequestTestJob(request,
1652 network_delegate,
1653 final_headers_,
1654 final_data_,
1655 true);
1656 }
1657
1658 void set_intercept_main_request(bool intercept_main_request) {
1659 intercept_main_request_ = intercept_main_request;
1660 }
1661
1662 void set_main_headers(const std::string& main_headers) {
1663 main_headers_ = main_headers;
1664 }
1665
1666 void set_main_data(const std::string& main_data) {
1667 main_data_ = main_data;
1668 }
1669
1670 void set_main_request_load_timing_info(
1671 const LoadTimingInfo& main_request_load_timing_info) {
1672 main_request_load_timing_info_ = main_request_load_timing_info;
1673 }
1674
1675 void set_restart_main_request(bool restart_main_request) {
1676 restart_main_request_ = restart_main_request;
1677 }
1678
1679 void set_cancel_main_request(bool cancel_main_request) {
1680 cancel_main_request_ = cancel_main_request;
1681 }
1682
1683 void set_cancel_then_restart_main_request(
1684 bool cancel_then_restart_main_request) {
1685 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1686 }
1687
1688 void set_simulate_main_network_error(bool simulate_main_network_error) {
1689 simulate_main_network_error_ = simulate_main_network_error;
1690 }
1691
1692 void set_intercept_redirect(bool intercept_redirect) {
1693 intercept_redirect_ = intercept_redirect;
1694 }
1695
1696 void set_redirect_headers(const std::string& redirect_headers) {
1697 redirect_headers_ = redirect_headers;
1698 }
1699
1700 void set_redirect_data(const std::string& redirect_data) {
1701 redirect_data_ = redirect_data;
1702 }
1703
1704 void set_cancel_redirect_request(bool cancel_redirect_request) {
1705 cancel_redirect_request_ = cancel_redirect_request;
1706 }
1707
1708 void set_intercept_final_response(bool intercept_final_response) {
1709 intercept_final_response_ = intercept_final_response;
1710 }
1711
1712 void set_final_headers(const std::string& final_headers) {
1713 final_headers_ = final_headers;
1714 }
1715
1716 void set_final_data(const std::string& final_data) {
1717 final_data_ = final_data;
1718 }
1719
1720 void set_cancel_final_request(bool cancel_final_request) {
1721 cancel_final_request_ = cancel_final_request;
1722 }
1723
1724 void set_use_url_request_http_job(bool use_url_request_http_job) {
1725 use_url_request_http_job_ = use_url_request_http_job;
1726 }
1727
1728 bool did_intercept_main() const {
1729 return did_intercept_main_;
1730 }
1731
1732 bool did_restart_main() const {
1733 return did_restart_main_;
1734 }
1735
1736 bool did_cancel_main() const {
1737 return did_cancel_main_;
1738 }
1739
1740 bool did_cancel_then_restart_main() const {
1741 return did_cancel_then_restart_main_;
1742 }
1743
1744 bool did_simulate_error_main() const {
1745 return did_simulate_error_main_;
1746 }
1747
1748 bool did_intercept_redirect() const {
1749 return did_intercept_redirect_;
1750 }
1751
1752 bool did_cancel_redirect() const {
1753 return did_cancel_redirect_;
1754 }
1755
1756 bool did_intercept_final() const {
1757 return did_intercept_final_;
1758 }
1759
1760 bool did_cancel_final() const {
1761 return did_cancel_final_;
1762 }
1763
1764 private:
1765 // Indicate whether to intercept the main request, and if so specify the
1766 // response to return and the LoadTimingInfo to use.
1767 mutable bool intercept_main_request_;
1768 mutable std::string main_headers_;
1769 mutable std::string main_data_;
1770 mutable LoadTimingInfo main_request_load_timing_info_;
1771
1772 // These indicate actions that can be taken within MaybeInterceptRequest.
1773 mutable bool restart_main_request_;
1774 mutable bool cancel_main_request_;
1775 mutable bool cancel_then_restart_main_request_;
1776 mutable bool simulate_main_network_error_;
1777
1778 // Indicate whether to intercept redirects, and if so specify the response to
1779 // return.
1780 mutable bool intercept_redirect_;
1781 mutable std::string redirect_headers_;
1782 mutable std::string redirect_data_;
1783
1784 // Cancel the request within MaybeInterceptRedirect.
1785 mutable bool cancel_redirect_request_;
1786
1787 // Indicate whether to intercept the final response, and if so specify the
1788 // response to return.
1789 mutable bool intercept_final_response_;
1790 mutable std::string final_headers_;
1791 mutable std::string final_data_;
1792
1793 // Cancel the final request within MaybeInterceptResponse.
1794 mutable bool cancel_final_request_;
1795
1796 // Instruct the interceptor to use a real URLRequestHTTPJob.
1797 mutable bool use_url_request_http_job_;
1798
1799 // These indicate if the interceptor did something or not.
1800 mutable bool did_intercept_main_;
1801 mutable bool did_restart_main_;
1802 mutable bool did_cancel_main_;
1803 mutable bool did_cancel_then_restart_main_;
1804 mutable bool did_simulate_error_main_;
1805 mutable bool did_intercept_redirect_;
1806 mutable bool did_cancel_redirect_;
1807 mutable bool did_intercept_final_;
1808 mutable bool did_cancel_final_;
1809};
1810
1811// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1812class URLRequestInterceptorTest : public URLRequestTest {
1813 public:
1814 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1815 }
1816
1817 ~URLRequestInterceptorTest() override {
1818 // URLRequestJobs may post clean-up tasks on destruction.
1819 base::RunLoop().RunUntilIdle();
1820 }
1821
1822 void SetUpFactory() override {
1823 interceptor_ = new MockURLRequestInterceptor();
1824 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361825 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501826 }
1827
1828 MockURLRequestInterceptor* interceptor() const {
1829 return interceptor_;
1830 }
1831
1832 private:
1833 MockURLRequestInterceptor* interceptor_;
1834};
1835
1836TEST_F(URLRequestInterceptorTest, Intercept) {
1837 // Intercept the main request and respond with a simple response.
1838 interceptor()->set_intercept_main_request(true);
1839 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1840 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591841 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361842 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161843 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1844 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501845 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1846 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1847 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
Randy Smith4cd4d36a2017-08-24 01:01:091848 req->SetUserData(&user_data0, base::WrapUnique(user_data0));
avi0d991472017-04-27 07:04:041849 req->SetUserData(&user_data1, base::WrapUnique(user_data1));
1850 req->SetUserData(&user_data2, base::WrapUnique(user_data2));
bengr1bf8e942014-11-07 01:36:501851 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191852 req->Start();
[email protected]255620da2013-08-19 13:14:291853 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591854
bengr1bf8e942014-11-07 01:36:501855 // Make sure we can retrieve our specific user data.
Randy Smith4cd4d36a2017-08-24 01:01:091856 EXPECT_EQ(user_data0, req->GetUserData(&user_data0));
bengr1bf8e942014-11-07 01:36:501857 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1858 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591859
bengr1bf8e942014-11-07 01:36:501860 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501861 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501862 EXPECT_EQ(200, req->response_headers()->response_code());
1863 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1864 EXPECT_EQ(1, d.response_started_count());
1865 EXPECT_EQ(0, d.received_redirect_count());
1866}
[email protected]2bba3252013-04-08 19:50:591867
bengr1bf8e942014-11-07 01:36:501868TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1869 // Intercept the main request and respond with a redirect.
1870 interceptor()->set_intercept_main_request(true);
1871 interceptor()->set_main_headers(
1872 MockURLRequestInterceptor::redirect_headers());
1873 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1874
1875 // Intercept that redirect and respond with a final OK response.
1876 interceptor()->set_intercept_redirect(true);
1877 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1878 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1879
1880 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361881 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161882 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1883 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501884 req->set_method("GET");
1885 req->Start();
1886 base::RunLoop().Run();
1887
1888 // Check that the interceptor got called as expected.
1889 EXPECT_TRUE(interceptor()->did_intercept_main());
1890 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1891
1892 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501893 int status = d.request_status();
1894 EXPECT_EQ(OK, status);
1895 if (status == OK)
bengr1bf8e942014-11-07 01:36:501896 EXPECT_EQ(200, req->response_headers()->response_code());
1897
1898 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1899 EXPECT_EQ(1, d.response_started_count());
1900 EXPECT_EQ(0, d.received_redirect_count());
1901}
1902
1903TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1904 // Intercept the main request to generate a server error response.
1905 interceptor()->set_intercept_main_request(true);
1906 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1907 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1908
1909 // Intercept that error and respond with an OK response.
1910 interceptor()->set_intercept_final_response(true);
1911 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1912 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1913
1914 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361915 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161916 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1917 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501918 req->set_method("GET");
1919 req->Start();
1920 base::RunLoop().Run();
1921
1922 // Check that the interceptor got called as expected.
1923 EXPECT_TRUE(interceptor()->did_intercept_main());
1924 EXPECT_TRUE(interceptor()->did_intercept_final());
1925
1926 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501927 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501928 EXPECT_EQ(200, req->response_headers()->response_code());
1929 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1930 EXPECT_EQ(1, d.response_started_count());
1931 EXPECT_EQ(0, d.received_redirect_count());
1932}
1933
1934TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1935 // Intercept the main request to simulate a network error.
1936 interceptor()->set_simulate_main_network_error(true);
1937
1938 // Intercept that error and respond with an OK response.
1939 interceptor()->set_intercept_final_response(true);
1940 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1941 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1942
1943 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361944 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161945 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1946 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501947 req->set_method("GET");
1948 req->Start();
1949 base::RunLoop().Run();
1950
1951 // Check that the interceptor got called as expected.
1952 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1953 EXPECT_TRUE(interceptor()->did_intercept_final());
1954
1955 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501956 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501957 EXPECT_EQ(200, req->response_headers()->response_code());
1958 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1959 EXPECT_EQ(1, d.response_started_count());
1960 EXPECT_EQ(0, d.received_redirect_count());
1961}
1962
1963TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1964 // Restart the main request.
1965 interceptor()->set_restart_main_request(true);
1966
1967 // then intercept the new main request and respond with an OK response
1968 interceptor()->set_intercept_main_request(true);
1969 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1970 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1971
1972 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361973 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161974 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1975 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501976 req->set_method("GET");
1977 req->Start();
1978 base::RunLoop().Run();
1979
1980 // Check that the interceptor got called as expected.
1981 EXPECT_TRUE(interceptor()->did_restart_main());
1982 EXPECT_TRUE(interceptor()->did_intercept_main());
1983
1984 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501985 int status = d.request_status();
1986 EXPECT_EQ(OK, status);
1987 if (status == OK)
bengr1bf8e942014-11-07 01:36:501988 EXPECT_EQ(200, req->response_headers()->response_code());
1989
1990 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1991 EXPECT_EQ(1, d.response_started_count());
1992 EXPECT_EQ(0, d.received_redirect_count());
1993}
1994
1995TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1996 // Intercept the main request and cancel from within the restarted job.
1997 interceptor()->set_cancel_main_request(true);
1998
1999 // Set up to intercept the final response and override it with an OK response.
2000 interceptor()->set_intercept_final_response(true);
2001 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2002 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2003
2004 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362005 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162006 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2007 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502008 req->set_method("GET");
2009 req->Start();
2010 base::RunLoop().Run();
2011
2012 // Check that the interceptor got called as expected.
2013 EXPECT_TRUE(interceptor()->did_cancel_main());
2014 EXPECT_FALSE(interceptor()->did_intercept_final());
2015
2016 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502017 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502018}
2019
2020TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2021 // Intercept the main request and respond with a redirect.
2022 interceptor()->set_intercept_main_request(true);
2023 interceptor()->set_main_headers(
2024 MockURLRequestInterceptor::redirect_headers());
2025 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2026
2027 // Intercept the redirect and cancel from within that job.
2028 interceptor()->set_cancel_redirect_request(true);
2029
2030 // Set up to intercept the final response and override it with an OK response.
2031 interceptor()->set_intercept_final_response(true);
2032 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2033 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2034
2035 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362036 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162037 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2038 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502039 req->set_method("GET");
2040 req->Start();
2041 base::RunLoop().Run();
2042
2043 // Check that the interceptor got called as expected.
2044 EXPECT_TRUE(interceptor()->did_intercept_main());
2045 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2046 EXPECT_FALSE(interceptor()->did_intercept_final());
2047
2048 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502049 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502050}
2051
2052TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2053 // Intercept the main request to simulate a network error.
2054 interceptor()->set_simulate_main_network_error(true);
2055
2056 // Set up to intercept final the response and cancel from within that job.
2057 interceptor()->set_cancel_final_request(true);
2058
2059 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362060 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162061 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2062 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502063 req->set_method("GET");
2064 req->Start();
2065 base::RunLoop().Run();
2066
2067 // Check that the interceptor got called as expected.
2068 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2069 EXPECT_TRUE(interceptor()->did_cancel_final());
2070
2071 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502072 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502073}
2074
2075TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2076 // Intercept the main request and cancel then restart from within that job.
2077 interceptor()->set_cancel_then_restart_main_request(true);
2078
2079 // Set up to intercept the final response and override it with an OK response.
2080 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:502081 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2082 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:502083
2084 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362085 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162086 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2087 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502088 req->set_method("GET");
2089 req->Start();
2090 base::RunLoop().Run();
2091
2092 // Check that the interceptor got called as expected.
2093 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2094 EXPECT_FALSE(interceptor()->did_intercept_final());
2095
2096 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502097 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:592098}
2099
2100// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2101// reused. |connect_time_flags| is used to indicate if there should be dns
2102// or SSL times, and |used_proxy| is used for proxy times.
2103LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2104 int connect_time_flags,
2105 bool used_proxy) {
2106 LoadTimingInfo load_timing;
2107 load_timing.socket_log_id = 1;
2108
2109 if (used_proxy) {
2110 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2111 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2112 }
2113
2114 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2115 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2116 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2117 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2118 }
2119 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2120 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2121 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2122 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2123 }
2124 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2125
2126 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2127 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2128 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2129 return load_timing;
2130}
2131
2132// Same as above, but in the case of a reused socket.
2133LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2134 bool used_proxy) {
2135 LoadTimingInfo load_timing;
2136 load_timing.socket_log_id = 1;
2137 load_timing.socket_reused = true;
2138
2139 if (used_proxy) {
2140 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2141 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2142 }
2143
2144 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2145 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2146 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2147 return load_timing;
2148}
2149
bengr1bf8e942014-11-07 01:36:502150LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2151 const LoadTimingInfo& job_load_timing,
2152 const URLRequestContext& context,
2153 MockURLRequestInterceptor* interceptor) {
2154 interceptor->set_intercept_main_request(true);
2155 interceptor->set_main_request_load_timing_info(job_load_timing);
2156 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162157 std::unique_ptr<URLRequest> req(
2158 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2159 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502160 req->Start();
2161 base::RunLoop().Run();
2162
2163 LoadTimingInfo resulting_load_timing;
2164 req->GetLoadTimingInfo(&resulting_load_timing);
2165
2166 // None of these should be modified by the URLRequest.
2167 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2168 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2169 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2170 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
2171 EXPECT_EQ(job_load_timing.receive_headers_end,
2172 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572173 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2174 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502175
2176 return resulting_load_timing;
2177}
2178
[email protected]2bba3252013-04-08 19:50:592179// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502180TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592181 base::TimeTicks now = base::TimeTicks::Now();
2182 LoadTimingInfo job_load_timing =
2183 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2184
[email protected]2ca01e52013-10-31 22:05:192185 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502186 RunURLRequestInterceptorLoadTimingTest(
2187 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592188
2189 // Nothing should have been changed by the URLRequest.
2190 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2191 load_timing_result.proxy_resolve_start);
2192 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2193 load_timing_result.proxy_resolve_end);
2194 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2195 load_timing_result.connect_timing.dns_start);
2196 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2197 load_timing_result.connect_timing.dns_end);
2198 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2199 load_timing_result.connect_timing.connect_start);
2200 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2201 load_timing_result.connect_timing.connect_end);
2202 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2203 load_timing_result.connect_timing.ssl_start);
2204 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2205 load_timing_result.connect_timing.ssl_end);
2206
2207 // Redundant sanity check.
2208 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2209}
2210
2211// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502212TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592213 base::TimeTicks now = base::TimeTicks::Now();
2214 LoadTimingInfo job_load_timing =
2215 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2216
[email protected]2ca01e52013-10-31 22:05:192217 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502218 RunURLRequestInterceptorLoadTimingTest(
2219 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592220
2221 // Nothing should have been changed by the URLRequest.
2222 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2223 load_timing_result.proxy_resolve_start);
2224 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2225 load_timing_result.proxy_resolve_end);
2226 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2227 load_timing_result.connect_timing.dns_start);
2228 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2229 load_timing_result.connect_timing.dns_end);
2230 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2231 load_timing_result.connect_timing.connect_start);
2232 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2233 load_timing_result.connect_timing.connect_end);
2234 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2235 load_timing_result.connect_timing.ssl_start);
2236 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2237 load_timing_result.connect_timing.ssl_end);
2238
2239 // Redundant sanity check.
2240 TestLoadTimingNotReusedWithProxy(load_timing_result,
2241 CONNECT_TIMING_HAS_SSL_TIMES);
2242}
2243
2244// Make sure that URLRequest correctly adjusts proxy times when they're before
2245// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102246// the case of reusing a SPDY session. The connected socket is not considered
2247// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592248//
2249// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502250TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592251 base::TimeTicks now = base::TimeTicks::Now();
2252 LoadTimingInfo job_load_timing =
2253 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2254 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2255 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2256 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2257 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2258 job_load_timing.connect_timing.connect_start =
2259 now - base::TimeDelta::FromDays(2);
2260 job_load_timing.connect_timing.connect_end =
2261 now - base::TimeDelta::FromDays(1);
2262
[email protected]2ca01e52013-10-31 22:05:192263 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502264 RunURLRequestInterceptorLoadTimingTest(
2265 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592266
2267 // Proxy times, connect times, and DNS times should all be replaced with
2268 // request_start.
2269 EXPECT_EQ(load_timing_result.request_start,
2270 load_timing_result.proxy_resolve_start);
2271 EXPECT_EQ(load_timing_result.request_start,
2272 load_timing_result.proxy_resolve_end);
2273 EXPECT_EQ(load_timing_result.request_start,
2274 load_timing_result.connect_timing.dns_start);
2275 EXPECT_EQ(load_timing_result.request_start,
2276 load_timing_result.connect_timing.dns_end);
2277 EXPECT_EQ(load_timing_result.request_start,
2278 load_timing_result.connect_timing.connect_start);
2279 EXPECT_EQ(load_timing_result.request_start,
2280 load_timing_result.connect_timing.connect_end);
2281
2282 // Other times should have been left null.
2283 TestLoadTimingNotReusedWithProxy(load_timing_result,
2284 CONNECT_TIMING_HAS_DNS_TIMES);
2285}
2286
2287// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502288TEST_F(URLRequestInterceptorTest,
2289 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592290 base::TimeTicks now = base::TimeTicks::Now();
2291 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2292 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2293 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2294
[email protected]2ca01e52013-10-31 22:05:192295 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502296 RunURLRequestInterceptorLoadTimingTest(
2297 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592298
2299 // Proxy times and connect times should all be replaced with request_start.
2300 EXPECT_EQ(load_timing_result.request_start,
2301 load_timing_result.proxy_resolve_start);
2302 EXPECT_EQ(load_timing_result.request_start,
2303 load_timing_result.proxy_resolve_end);
2304
2305 // Other times should have been left null.
2306 TestLoadTimingReusedWithProxy(load_timing_result);
2307}
2308
2309// Make sure that URLRequest correctly adjusts connect times when they're before
2310// |request_start|, due to reusing a connected socket. The connected socket is
2311// not considered reused in this test (May be a preconnect).
2312//
2313// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502314TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592315 base::TimeTicks now = base::TimeTicks::Now();
2316 LoadTimingInfo job_load_timing =
2317 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2318 job_load_timing.connect_timing.connect_start =
2319 now - base::TimeDelta::FromDays(1);
2320 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2321 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2322 job_load_timing.connect_timing.connect_end =
2323 now - base::TimeDelta::FromDays(4);
2324
[email protected]2ca01e52013-10-31 22:05:192325 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502326 RunURLRequestInterceptorLoadTimingTest(
2327 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592328
2329 // Connect times, and SSL times should be replaced with request_start.
2330 EXPECT_EQ(load_timing_result.request_start,
2331 load_timing_result.connect_timing.connect_start);
2332 EXPECT_EQ(load_timing_result.request_start,
2333 load_timing_result.connect_timing.ssl_start);
2334 EXPECT_EQ(load_timing_result.request_start,
2335 load_timing_result.connect_timing.ssl_end);
2336 EXPECT_EQ(load_timing_result.request_start,
2337 load_timing_result.connect_timing.connect_end);
2338
2339 // Other times should have been left null.
2340 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2341}
2342
2343// Make sure that URLRequest correctly adjusts connect times when they're before
2344// |request_start|, due to reusing a connected socket in the case that there
2345// are also proxy times. The connected socket is not considered reused in this
2346// test (May be a preconnect).
2347//
2348// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502349TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592350 base::TimeTicks now = base::TimeTicks::Now();
2351 LoadTimingInfo job_load_timing =
2352 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2353 job_load_timing.connect_timing.connect_start =
2354 now - base::TimeDelta::FromDays(1);
2355 job_load_timing.connect_timing.connect_end =
2356 now - base::TimeDelta::FromDays(2);
2357
[email protected]2ca01e52013-10-31 22:05:192358 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502359 RunURLRequestInterceptorLoadTimingTest(
2360 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592361
2362 // Connect times should be replaced with proxy_resolve_end.
2363 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2364 load_timing_result.connect_timing.connect_start);
2365 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2366 load_timing_result.connect_timing.connect_end);
2367
2368 // Other times should have been left null.
2369 TestLoadTimingNotReusedWithProxy(load_timing_result,
2370 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2371}
2372
[email protected]316c1e5e2012-09-12 15:17:442373// Check that two different URL requests have different identifiers.
2374TEST_F(URLRequestTest, Identifiers) {
2375 TestDelegate d;
2376 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362377 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162378 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2379 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362380 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162381 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2382 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442383
mmenke19378d22014-09-09 04:12:592384 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442385}
2386
blundellb8163592f2015-12-16 14:22:422387#if defined(OS_IOS)
2388// TODO(droger): Check that a failure to connect to the proxy is reported to
2389// the network delegate. crbug.com/496743
2390#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2391#else
2392#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2393#endif
2394TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442395 MockHostResolver host_resolver;
2396 host_resolver.rules()->AddSimulatedFailure("*");
2397
[email protected]ceefd7fd2012-11-29 00:36:242398 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442399 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2400
2401 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362402 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162403 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2404 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192405 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442406
[email protected]f7022f32014-08-21 16:32:192407 req->Start();
[email protected]255620da2013-08-19 13:14:292408 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442409
2410 // Check we see a failed request.
[email protected]d8fc4722014-06-13 13:17:152411 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472412 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502413 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442414
2415 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012416 EXPECT_THAT(network_delegate.last_error(),
2417 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442418 EXPECT_EQ(1, network_delegate.completed_requests());
2419}
2420
[email protected]cba24642014-08-15 20:49:592421// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442422// content is empty.
2423TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2424 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162425 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
2426 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192427 req->Start();
[email protected]255620da2013-08-19 13:14:292428 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442429 EXPECT_EQ("", d.data_received());
2430 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2431}
2432
[email protected]5033ab82013-03-22 20:17:462433// Make sure that SetPriority actually sets the URLRequest's priority
2434// correctly, both before and after start.
2435TEST_F(URLRequestTest, SetPriorityBasic) {
2436 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362437 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162438 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2439 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192440 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462441
[email protected]f7022f32014-08-21 16:32:192442 req->SetPriority(LOW);
2443 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462444
[email protected]f7022f32014-08-21 16:32:192445 req->Start();
2446 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462447
[email protected]f7022f32014-08-21 16:32:192448 req->SetPriority(MEDIUM);
2449 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462450}
2451
2452// Make sure that URLRequest calls SetPriority on a job before calling
2453// Start on it.
2454TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2455 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362456 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162457 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2458 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192459 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462460
mmenkeed0498b2015-12-08 23:20:422461 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362462 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422463 req.get(), &default_network_delegate_, &job_priority));
2464 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2465 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462466
[email protected]f7022f32014-08-21 16:32:192467 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462468
[email protected]f7022f32014-08-21 16:32:192469 req->Start();
mmenkeed0498b2015-12-08 23:20:422470 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462471}
2472
2473// Make sure that URLRequest passes on its priority updates to its
2474// job.
2475TEST_F(URLRequestTest, SetJobPriority) {
2476 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362477 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162478 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2479 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5033ab82013-03-22 20:17:462480
mmenkeed0498b2015-12-08 23:20:422481 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362482 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422483 req.get(), &default_network_delegate_, &job_priority));
2484 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462485
[email protected]f7022f32014-08-21 16:32:192486 req->SetPriority(LOW);
2487 req->Start();
mmenkeed0498b2015-12-08 23:20:422488 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462489
[email protected]f7022f32014-08-21 16:32:192490 req->SetPriority(MEDIUM);
2491 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422492 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462493}
2494
[email protected]bb1c4662013-11-14 00:00:072495// Setting the IGNORE_LIMITS load flag should be okay if the priority
2496// is MAXIMUM_PRIORITY.
2497TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2498 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362499 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162500 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2501 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192502 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072503
mmenkeed0498b2015-12-08 23:20:422504 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362505 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422506 req.get(), &default_network_delegate_, &job_priority));
2507 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072508
[email protected]f7022f32014-08-21 16:32:192509 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2510 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072511
[email protected]f7022f32014-08-21 16:32:192512 req->SetPriority(MAXIMUM_PRIORITY);
2513 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072514
[email protected]f7022f32014-08-21 16:32:192515 req->Start();
2516 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422517 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072518}
2519
nick5d570de92015-05-04 20:16:162520namespace {
2521
2522// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552523class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442524 public:
tommycli59a63432015-11-06 00:10:552525 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2526 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272527 }
tommycli59a63432015-11-06 00:10:552528
2529 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2530};
tommyclieae5f75f2015-11-05 19:07:272531
nick5d570de92015-05-04 20:16:162532} // namespace
2533
[email protected]f2f31b32013-01-16 23:24:092534TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442535 LocalHttpTestServer test_server;
2536 ASSERT_TRUE(test_server.Start());
2537
2538 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362539 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502540 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442541
2542 // Set up a cookie.
2543 {
2544 TestNetworkDelegate network_delegate;
2545 context.set_network_delegate(&network_delegate);
2546 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362547 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552548 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162549 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192550 req->Start();
[email protected]255620da2013-08-19 13:14:292551 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442552 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2553 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2554 EXPECT_EQ(1, network_delegate.set_cookie_count());
2555 }
2556
2557 // Verify that the cookie is set.
2558 {
2559 TestNetworkDelegate network_delegate;
2560 context.set_network_delegate(&network_delegate);
2561 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362562 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162563 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2564 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192565 req->Start();
[email protected]255620da2013-08-19 13:14:292566 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442567
2568 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2569 != std::string::npos);
2570 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2571 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2572 }
2573}
2574
[email protected]f2f31b32013-01-16 23:24:092575TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442576 LocalHttpTestServer test_server;
2577 ASSERT_TRUE(test_server.Start());
2578
2579 // Set up a cookie.
2580 {
2581 TestNetworkDelegate network_delegate;
2582 default_context_.set_network_delegate(&network_delegate);
2583 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362584 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552585 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162586 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192587 req->Start();
[email protected]255620da2013-08-19 13:14:292588 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442589 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2590 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2591 }
2592
2593 // Verify that the cookie is set.
2594 {
2595 TestNetworkDelegate network_delegate;
2596 default_context_.set_network_delegate(&network_delegate);
2597 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362598 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162599 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2600 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192601 req->Start();
[email protected]255620da2013-08-19 13:14:292602 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442603
2604 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2605 != std::string::npos);
2606 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2607 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2608 }
2609
2610 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2611 {
2612 TestNetworkDelegate network_delegate;
2613 default_context_.set_network_delegate(&network_delegate);
2614 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362615 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162616 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2617 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192618 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2619 req->Start();
[email protected]255620da2013-08-19 13:14:292620 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442621
2622 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2623 == std::string::npos);
2624
2625 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2626 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2627 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2628 }
2629}
2630
2631TEST_F(URLRequestTest, DoNotSaveCookies) {
2632 LocalHttpTestServer test_server;
2633 ASSERT_TRUE(test_server.Start());
2634
2635 // Set up a cookie.
2636 {
2637 TestNetworkDelegate network_delegate;
2638 default_context_.set_network_delegate(&network_delegate);
2639 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362640 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552641 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162642 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192643 req->Start();
[email protected]255620da2013-08-19 13:14:292644 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442645
2646 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2647 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2648 EXPECT_EQ(1, network_delegate.set_cookie_count());
2649 }
2650
2651 // Try to set-up another cookie and update the previous cookie.
2652 {
2653 TestNetworkDelegate network_delegate;
2654 default_context_.set_network_delegate(&network_delegate);
2655 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362656 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552657 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162658 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192659 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2660 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442661
[email protected]255620da2013-08-19 13:14:292662 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442663
2664 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2665 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2666 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2667 EXPECT_EQ(0, network_delegate.set_cookie_count());
2668 }
2669
2670 // Verify the cookies weren't saved or updated.
2671 {
2672 TestNetworkDelegate network_delegate;
2673 default_context_.set_network_delegate(&network_delegate);
2674 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362675 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162676 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2677 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192678 req->Start();
[email protected]255620da2013-08-19 13:14:292679 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442680
2681 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2682 == std::string::npos);
2683 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2684 != std::string::npos);
2685
2686 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2687 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2688 EXPECT_EQ(0, network_delegate.set_cookie_count());
2689 }
2690}
2691
2692TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2693 LocalHttpTestServer test_server;
2694 ASSERT_TRUE(test_server.Start());
2695
2696 // Set up a cookie.
2697 {
2698 TestNetworkDelegate network_delegate;
2699 default_context_.set_network_delegate(&network_delegate);
2700 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362701 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552702 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162703 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192704 req->Start();
[email protected]255620da2013-08-19 13:14:292705 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442706
2707 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2708 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2709 }
2710
2711 // Verify that the cookie is set.
2712 {
2713 TestNetworkDelegate network_delegate;
2714 default_context_.set_network_delegate(&network_delegate);
2715 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362716 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162717 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2718 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192719 req->Start();
[email protected]255620da2013-08-19 13:14:292720 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442721
2722 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2723 != std::string::npos);
2724
2725 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2726 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2727 }
2728
2729 // Verify that the cookie isn't sent.
2730 {
2731 TestNetworkDelegate network_delegate;
2732 default_context_.set_network_delegate(&network_delegate);
2733 TestDelegate d;
2734 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362735 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162736 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2737 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192738 req->Start();
[email protected]255620da2013-08-19 13:14:292739 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442740
2741 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2742 == std::string::npos);
2743
[email protected]22e045f2013-09-20 03:54:032744 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442745 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2746 }
2747}
2748
marqf14fff8d2015-12-02 15:52:292749// TODO(crbug.com/564656) This test is flaky on iOS.
2750#if defined(OS_IOS)
2751#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2752#else
2753#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2754#endif
[email protected]316c1e5e2012-09-12 15:17:442755TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2756 LocalHttpTestServer test_server;
2757 ASSERT_TRUE(test_server.Start());
2758
2759 // Set up a cookie.
2760 {
2761 TestNetworkDelegate network_delegate;
2762 default_context_.set_network_delegate(&network_delegate);
2763 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362764 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552765 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162766 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192767 req->Start();
[email protected]255620da2013-08-19 13:14:292768 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442769
2770 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2771 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2772 }
2773
2774 // Try to set-up another cookie and update the previous cookie.
2775 {
2776 TestNetworkDelegate network_delegate;
2777 default_context_.set_network_delegate(&network_delegate);
2778 TestDelegate d;
2779 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362780 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552781 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162782 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192783 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442784
[email protected]255620da2013-08-19 13:14:292785 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442786
2787 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2788 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2789 }
2790
2791 // Verify the cookies weren't saved or updated.
2792 {
2793 TestNetworkDelegate network_delegate;
2794 default_context_.set_network_delegate(&network_delegate);
2795 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362796 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162797 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2798 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192799 req->Start();
[email protected]255620da2013-08-19 13:14:292800 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442801
2802 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2803 == std::string::npos);
2804 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2805 != std::string::npos);
2806
2807 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2808 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2809 }
2810}
2811
2812TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2813 LocalHttpTestServer test_server;
2814 ASSERT_TRUE(test_server.Start());
2815
2816 // Set up an empty cookie.
2817 {
2818 TestNetworkDelegate network_delegate;
2819 default_context_.set_network_delegate(&network_delegate);
2820 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362821 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162822 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
2823 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192824 req->Start();
[email protected]255620da2013-08-19 13:14:292825 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442826
2827 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2828 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2829 EXPECT_EQ(0, network_delegate.set_cookie_count());
2830 }
2831}
2832
2833TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2834 LocalHttpTestServer test_server;
2835 ASSERT_TRUE(test_server.Start());
2836
2837 // Set up a cookie.
2838 {
2839 TestNetworkDelegate network_delegate;
2840 default_context_.set_network_delegate(&network_delegate);
2841 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362842 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552843 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162844 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192845 req->Start();
[email protected]255620da2013-08-19 13:14:292846 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442847
2848 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2849 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2850 }
2851
2852 // Verify that the cookie is set.
2853 {
2854 TestNetworkDelegate network_delegate;
2855 default_context_.set_network_delegate(&network_delegate);
2856 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362857 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162858 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2859 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192860 req->Start();
[email protected]255620da2013-08-19 13:14:292861 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442862
2863 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2864 != std::string::npos);
2865
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 isn't sent.
2871 {
2872 TestNetworkDelegate network_delegate;
2873 default_context_.set_network_delegate(&network_delegate);
2874 TestDelegate d;
2875 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362876 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162877 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2878 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192879 req->Start();
[email protected]255620da2013-08-19 13:14:292880 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442881
2882 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2883 == std::string::npos);
2884
[email protected]22e045f2013-09-20 03:54:032885 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442886 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2887 }
2888}
2889
2890TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2891 LocalHttpTestServer test_server;
2892 ASSERT_TRUE(test_server.Start());
2893
2894 // Set up a cookie.
2895 {
2896 TestNetworkDelegate network_delegate;
2897 default_context_.set_network_delegate(&network_delegate);
2898 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362899 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552900 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162901 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192902 req->Start();
[email protected]255620da2013-08-19 13:14:292903 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442904
2905 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2906 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2907 }
2908
2909 // Try to set-up another cookie and update the previous cookie.
2910 {
2911 TestNetworkDelegate network_delegate;
2912 default_context_.set_network_delegate(&network_delegate);
2913 TestDelegate d;
2914 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362915 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552916 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162917 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192918 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442919
[email protected]255620da2013-08-19 13:14:292920 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442921
2922 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2923 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2924 }
2925
2926 // Verify the cookies weren't saved or updated.
2927 {
2928 TestNetworkDelegate network_delegate;
2929 default_context_.set_network_delegate(&network_delegate);
2930 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362931 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162932 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2933 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192934 req->Start();
[email protected]255620da2013-08-19 13:14:292935 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442936
2937 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2938 == std::string::npos);
2939 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2940 != std::string::npos);
2941
2942 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2943 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2944 }
2945}
2946
mkwstc5fa7762016-03-28 09:28:232947TEST_F(URLRequestTest, SameSiteCookies) {
mkwst3f3daac2015-02-26 20:15:262948 LocalHttpTestServer test_server;
2949 ASSERT_TRUE(test_server.Start());
2950
mkwst202534e32016-01-15 16:07:152951 TestNetworkDelegate network_delegate;
mkwst202534e32016-01-15 16:07:152952 default_context_.set_network_delegate(&network_delegate);
2953
mkwstf71d0bd2016-03-21 14:15:242954 const std::string kHost = "example.test";
2955 const std::string kSubHost = "subdomain.example.test";
2956 const std::string kCrossHost = "cross-origin.test";
2957
2958 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262959 {
mkwst3f3daac2015-02-26 20:15:262960 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362961 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242962 test_server.GetURL(kHost,
2963 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2964 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:162965 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst3f3daac2015-02-26 20:15:262966 req->Start();
2967 base::RunLoop().Run();
2968 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2969 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:242970 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:262971 }
2972
mkwstf71d0bd2016-03-21 14:15:242973 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262974 {
mkwst3f3daac2015-02-26 20:15:262975 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362976 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162977 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2978 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:462979 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
mkwstf71d0bd2016-03-21 14:15:242980 req->set_initiator(url::Origin(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:262981 req->Start();
2982 base::RunLoop().Run();
2983
mkwstf71d0bd2016-03-21 14:15:242984 EXPECT_NE(std::string::npos,
2985 d.data_received().find("StrictSameSiteCookie=1"));
2986 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262987 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2988 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2989 }
2990
clamyfd58ca072016-12-21 17:18:322991 // Verify that both cookies are sent when the request has no initiator (can
2992 // happen for main frame browser-initiated navigations).
2993 {
2994 TestDelegate d;
2995 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162996 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2997 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:462998 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:322999 req->Start();
3000 base::RunLoop().Run();
3001
3002 EXPECT_NE(std::string::npos,
3003 d.data_received().find("StrictSameSiteCookie=1"));
3004 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3005 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3006 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3007 }
3008
mkwstf71d0bd2016-03-21 14:15:243009 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:263010 {
mkwst3f3daac2015-02-26 20:15:263011 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363012 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163013 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3014 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463015 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
mkwstf71d0bd2016-03-21 14:15:243016 req->set_initiator(url::Origin(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:153017 req->Start();
3018 base::RunLoop().Run();
3019
mkwstf71d0bd2016-03-21 14:15:243020 EXPECT_NE(std::string::npos,
3021 d.data_received().find("StrictSameSiteCookie=1"));
3022 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153023 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3024 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3025 }
3026
mkwstf71d0bd2016-03-21 14:15:243027 // Verify that neither cookie is not sent for cross-site requests.
3028 {
3029 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363030 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163031 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3032 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463033 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
mkwstf71d0bd2016-03-21 14:15:243034 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
3035 req->Start();
3036 base::RunLoop().Run();
3037
3038 EXPECT_EQ(std::string::npos,
3039 d.data_received().find("StrictSameSiteCookie=1"));
3040 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3041 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3042 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3043 }
3044
3045 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153046 // method is "safe".
3047 {
3048 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363049 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163050 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3051 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463052 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
mkwstf71d0bd2016-03-21 14:15:243053 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
3054 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153055 req->Start();
3056 base::RunLoop().Run();
3057
mkwstf71d0bd2016-03-21 14:15:243058 EXPECT_EQ(std::string::npos,
3059 d.data_received().find("StrictSameSiteCookie=1"));
3060 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153061 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3062 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3063 }
3064
mkwstf71d0bd2016-03-21 14:15:243065 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153066 // method is unsafe (e.g. POST).
3067 {
3068 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363069 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163070 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3071 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463072 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
mkwstf71d0bd2016-03-21 14:15:243073 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153074 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263075 req->Start();
3076 base::RunLoop().Run();
3077
mkwstf71d0bd2016-03-21 14:15:243078 EXPECT_EQ(std::string::npos,
3079 d.data_received().find("StrictSameSiteCookie=1"));
3080 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263081 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3082 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3083 }
3084}
3085
estark557a5eb82015-12-01 22:57:103086// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363087TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553088 EmbeddedTestServer http_server;
3089 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363090 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553091 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3092 https_server.AddDefaultHandlers(
3093 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3094 ASSERT_TRUE(http_server.Start());
3095 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363096
estarkb15166b2015-12-18 16:56:383097 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363098 TestURLRequestContext context(true);
3099 context.set_network_delegate(&network_delegate);
3100 context.Init();
3101
estarkb15166b2015-12-18 16:56:383102 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363103 {
3104 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363105 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103106 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163107 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363108 req->Start();
3109 base::RunLoop().Run();
3110 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3111 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3112 }
3113
3114 // Verify that the cookie is not set.
3115 {
3116 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363117 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163118 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3119 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363120 req->Start();
3121 base::RunLoop().Run();
3122
jww79aceda2015-12-07 01:56:343123 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3124 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363125 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3126 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3127 }
3128}
3129
estarkb15166b2015-12-18 16:56:383130TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553131 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3132 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363133 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553134 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363135
3136 TestNetworkDelegate network_delegate;
3137 TestURLRequestContext context(true);
3138 context.set_network_delegate(&network_delegate);
3139 context.Init();
3140
estarkb15166b2015-12-18 16:56:383141 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363142 {
3143 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163144 std::unique_ptr<URLRequest> req(context.CreateRequest(
3145 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3146 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363147 req->Start();
3148 base::RunLoop().Run();
3149 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3150 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3151 }
3152
3153 // Verify that the cookie is not set.
3154 {
3155 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363156 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163157 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3158 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363159 req->Start();
3160 base::RunLoop().Run();
3161
jww79aceda2015-12-07 01:56:343162 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363163 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3164 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3165 }
3166}
3167
estarkb15166b2015-12-18 16:56:383168TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553169 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3170 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363171 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553172 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363173
estarkb15166b2015-12-18 16:56:383174 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363175 TestURLRequestContext context(true);
3176 context.set_network_delegate(&network_delegate);
3177 context.Init();
3178
estarkb15166b2015-12-18 16:56:383179 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363180 {
3181 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363182 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103183 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163184 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363185 req->Start();
3186 base::RunLoop().Run();
3187 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3188 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3189 }
3190
3191 // Verify that the cookie is set.
3192 {
3193 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363194 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163195 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3196 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363197 req->Start();
3198 base::RunLoop().Run();
3199
jww79aceda2015-12-07 01:56:343200 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3201 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3202 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3203 }
3204}
3205
3206// Tests that secure cookies can't be set on non-secure origins if strict secure
3207// cookies are enabled.
3208TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3209 EmbeddedTestServer http_server;
3210 http_server.AddDefaultHandlers(
3211 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3212 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3213 https_server.AddDefaultHandlers(
3214 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3215 ASSERT_TRUE(http_server.Start());
3216 ASSERT_TRUE(https_server.Start());
3217
3218 TestExperimentalFeaturesNetworkDelegate network_delegate;
3219 TestURLRequestContext context(true);
3220 context.set_network_delegate(&network_delegate);
3221 context.Init();
3222
3223 // Try to set a Secure cookie, with experimental features enabled.
3224 {
3225 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363226 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343227 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163228 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343229 req->Start();
3230 base::RunLoop().Run();
3231 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3232 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3233 }
3234
3235 // Verify that the cookie is not set.
3236 {
3237 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363238 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163239 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3240 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343241 req->Start();
3242 base::RunLoop().Run();
3243
3244 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3245 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3246 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3247 }
3248}
3249
3250// Tests that secure cookies can be set on secure origins even if strict secure
3251// cookies are enabled.
3252TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
3253 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3254 https_server.AddDefaultHandlers(
3255 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3256 ASSERT_TRUE(https_server.Start());
3257
3258 TestExperimentalFeaturesNetworkDelegate network_delegate;
3259 TestURLRequestContext context(true);
3260 context.set_network_delegate(&network_delegate);
3261 context.Init();
3262
3263 // Try to set a Secure cookie, with experimental features enabled.
3264 {
3265 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363266 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343267 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163268 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343269 req->Start();
3270 base::RunLoop().Run();
3271 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3272 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3273 }
3274
3275 // Verify that the cookie is not set.
3276 {
3277 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363278 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163279 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3280 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343281 req->Start();
3282 base::RunLoop().Run();
3283
3284 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363285 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3286 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3287 }
3288}
3289
Mike West86149882017-07-28 10:41:493290TEST_F(URLRequestTest, CookieAgeMetrics) {
3291 EmbeddedTestServer http_server;
3292 http_server.AddDefaultHandlers(
3293 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3294 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3295 https_server.AddDefaultHandlers(
3296 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3297 ASSERT_TRUE(http_server.Start());
3298 ASSERT_TRUE(https_server.Start());
3299
3300 TestNetworkDelegate network_delegate;
3301 default_context_.set_network_delegate(&network_delegate);
3302 base::HistogramTester histograms;
3303
3304 const std::string kHost = "example.test";
3305 const std::string kCrossHost = "cross-origin.test";
3306
3307 // Set a test cookie.
3308 {
3309 TestDelegate d;
3310 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3311 http_server.GetURL(kHost, "/set-cookie?cookie=value"), DEFAULT_PRIORITY,
3312 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3313 req->Start();
3314 base::RunLoop().Run();
3315 ASSERT_EQ(1, network_delegate.set_cookie_count());
3316 }
3317
3318 // Make a secure request to `example.test`: we shouldn't record data.
3319 {
3320 TestDelegate d;
3321 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3322 https_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3323 TRAFFIC_ANNOTATION_FOR_TESTS));
3324 req->Start();
3325 base::RunLoop().Run();
3326 histograms.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3327 histograms.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3328 }
3329
3330 // Make a non-secure same-site request.
3331 {
3332 TestDelegate d;
3333 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3334 http_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3335 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463336 req->set_site_for_cookies(http_server.GetURL(kHost, "/"));
Mike West86149882017-07-28 10:41:493337 req->set_initiator(url::Origin(http_server.GetURL(kHost, "/")));
3338 req->Start();
3339 base::RunLoop().Run();
3340 histograms.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3341 histograms.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 1);
3342 }
3343
3344 // Make a non-secure cross-site request.
3345 {
3346 TestDelegate d;
3347 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3348 http_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3349 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463350 req->set_site_for_cookies(http_server.GetURL(kCrossHost, "/"));
Mike West86149882017-07-28 10:41:493351 req->set_initiator(url::Origin(http_server.GetURL(kCrossHost, "/")));
3352 req->Start();
3353 base::RunLoop().Run();
3354 histograms.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 1);
3355 histograms.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 1);
3356 }
3357}
3358
mmenkefb18c772015-09-30 22:22:503359// Tests that a request is cancelled while entering suspend mode. Uses mocks
3360// rather than a spawned test server because the connection used to talk to
3361// the test server is affected by entering suspend mode on Android.
3362TEST_F(URLRequestTest, CancelOnSuspend) {
3363 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363364 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503365
3366 URLRequestFailedJob::AddUrlHandler();
3367
3368 TestDelegate d;
3369 // Request that just hangs.
3370 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
rhalavatib7bd7c792017-04-27 05:25:163371 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3372 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mmenkefb18c772015-09-30 22:22:503373 r->Start();
3374
3375 power_monitor_source->Suspend();
3376 // Wait for the suspend notification to cause the request to fail.
3377 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:503378 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503379 EXPECT_TRUE(d.request_failed());
3380 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3381
3382 URLRequestFilter::GetInstance()->ClearHandlers();
3383
3384 // Shouldn't be needed, but just in case.
3385 power_monitor_source->Resume();
3386}
3387
[email protected]5095cd72012-11-01 10:29:163388// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3389// value for the |fixed_date| argument given to the constructor.
3390class FixedDateNetworkDelegate : public TestNetworkDelegate {
3391 public:
3392 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3393 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:203394 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163395
[email protected]cba24642014-08-15 20:49:593396 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203397 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593398 URLRequest* request,
3399 const CompletionCallback& callback,
3400 const HttpResponseHeaders* original_response_headers,
3401 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133402 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163403
3404 private:
3405 std::string fixed_date_;
3406
3407 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3408};
3409
3410int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593411 URLRequest* request,
3412 const CompletionCallback& callback,
3413 const HttpResponseHeaders* original_response_headers,
3414 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163415 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593416 HttpResponseHeaders* new_response_headers =
3417 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163418
3419 new_response_headers->RemoveHeader("Date");
3420 new_response_headers->AddHeader("Date: " + fixed_date_);
3421
3422 *override_response_headers = new_response_headers;
3423 return TestNetworkDelegate::OnHeadersReceived(request,
3424 callback,
3425 original_response_headers,
[email protected]5f714132014-03-26 10:41:163426 override_response_headers,
3427 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163428}
3429
3430// Test that cookie expiration times are adjusted for server/client clock
3431// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3432// headers by defaulting to GMT. (crbug.com/135131)
3433TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3434 LocalHttpTestServer test_server;
3435 ASSERT_TRUE(test_server.Start());
3436
3437 // Set up an expired cookie.
3438 {
3439 TestNetworkDelegate network_delegate;
3440 default_context_.set_network_delegate(&network_delegate);
3441 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363442 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193443 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553444 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163445 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193446 req->Start();
[email protected]255620da2013-08-19 13:14:293447 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163448 }
3449 // Verify that the cookie is not set.
3450 {
3451 TestNetworkDelegate network_delegate;
3452 default_context_.set_network_delegate(&network_delegate);
3453 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363454 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163455 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3456 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193457 req->Start();
[email protected]255620da2013-08-19 13:14:293458 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163459
3460 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3461 }
3462 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3463 {
3464 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3465 default_context_.set_network_delegate(&network_delegate);
3466 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363467 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193468 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553469 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163470 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193471 req->Start();
[email protected]255620da2013-08-19 13:14:293472 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163473 }
3474 // Verify that the cookie is set.
3475 {
3476 TestNetworkDelegate network_delegate;
3477 default_context_.set_network_delegate(&network_delegate);
3478 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363479 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163480 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3481 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193482 req->Start();
[email protected]255620da2013-08-19 13:14:293483 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163484
3485 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3486 }
3487}
3488
3489
[email protected]316c1e5e2012-09-12 15:17:443490// Check that it is impossible to change the referrer in the extra headers of
3491// an URLRequest.
3492TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3493 LocalHttpTestServer test_server;
3494 ASSERT_TRUE(test_server.Start());
3495
3496 // If extra headers contain referer and the request contains a referer,
3497 // only the latter shall be respected.
3498 {
3499 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363500 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163501 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3502 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193503 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443504
3505 HttpRequestHeaders headers;
3506 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193507 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443508
[email protected]f7022f32014-08-21 16:32:193509 req->Start();
[email protected]255620da2013-08-19 13:14:293510 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443511
3512 EXPECT_EQ("http://foo.com/", d.data_received());
3513 }
3514
3515 // If extra headers contain a referer but the request does not, no referer
3516 // shall be sent in the header.
3517 {
3518 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363519 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163520 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3521 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:443522
3523 HttpRequestHeaders headers;
3524 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193525 req->SetExtraRequestHeaders(headers);
3526 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443527
[email protected]f7022f32014-08-21 16:32:193528 req->Start();
[email protected]255620da2013-08-19 13:14:293529 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443530
3531 EXPECT_EQ("None", d.data_received());
3532 }
3533}
3534
[email protected]b89290212009-08-14 22:37:353535class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113536 public:
mmenke9f2ec60c2015-06-01 20:59:473537 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113538
[email protected]b89290212009-08-14 22:37:353539 protected:
[email protected]21184962011-10-26 00:50:303540 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3541 // |request_method| is the method to use for the initial request.
3542 // |redirect_method| is the method that is expected to be used for the second
3543 // request, after redirection.
3544 // If |include_data| is true, data is uploaded with the request. The
3545 // response body is expected to match it exactly, if and only if
3546 // |request_method| == |redirect_method|.
3547 void HTTPRedirectMethodTest(const GURL& redirect_url,
3548 const std::string& request_method,
3549 const std::string& redirect_method,
3550 bool include_data) {
3551 static const char kData[] = "hello world";
3552 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163553 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3554 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193555 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303556 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073557 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303558 HttpRequestHeaders headers;
3559 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513560 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543561 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193562 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303563 }
[email protected]f7022f32014-08-21 16:32:193564 req->Start();
[email protected]255620da2013-08-19 13:14:293565 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193566 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:503567 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:303568 if (include_data) {
3569 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543570 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3571 HttpRequestHeaders::kContentLength));
3572 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3573 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303574 EXPECT_EQ(kData, d.data_received());
3575 } else {
svaldez5b3a8972015-10-09 23:23:543576 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3577 HttpRequestHeaders::kContentLength));
3578 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3579 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303580 EXPECT_NE(kData, d.data_received());
3581 }
3582 }
3583 if (HasFailure())
3584 LOG(WARNING) << "Request method was: " << request_method;
3585 }
3586
jww5fe460ff2015-03-28 00:22:513587 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3588 // |request_method| is the method to use for the initial request.
3589 // |redirect_method| is the method that is expected to be used for the second
3590 // request, after redirection.
3591 // |origin_value| is the expected value for the Origin header after
3592 // redirection. If empty, expects that there will be no Origin header.
3593 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3594 const std::string& request_method,
3595 const std::string& redirect_method,
3596 const std::string& origin_value) {
3597 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163598 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3599 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:513600 req->set_method(request_method);
3601 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3602 redirect_url.GetOrigin().spec(), false);
3603 req->Start();
3604
3605 base::RunLoop().Run();
3606
3607 EXPECT_EQ(redirect_method, req->method());
3608 // Note that there is no check for request success here because, for
3609 // purposes of testing, the request very well may fail. For example, if the
3610 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3611 // origin, there is not an HTTPS server in this unit test framework, so the
3612 // request would fail. However, that's fine, as long as the request headers
3613 // are in order and pass the checks below.
3614 if (origin_value.empty()) {
3615 EXPECT_FALSE(
3616 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3617 } else {
3618 std::string origin_header;
3619 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3620 HttpRequestHeaders::kOrigin, &origin_header));
3621 EXPECT_EQ(origin_value, origin_header);
3622 }
3623 }
3624
[email protected]762d2db2010-01-11 19:03:013625 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013626 const int kMsgSize = 20000; // multiple of 10
3627 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483628 char* uploadBytes = new char[kMsgSize+1];
3629 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013630 char marker = 'a';
3631 for (int idx = 0; idx < kMsgSize/10; idx++) {
3632 memcpy(ptr, "----------", 10);
3633 ptr += 10;
3634 if (idx % 100 == 0) {
3635 ptr--;
3636 *ptr++ = marker;
3637 if (++marker > 'z')
3638 marker = 'a';
3639 }
3640 }
3641 uploadBytes[kMsgSize] = '\0';
3642
[email protected]762d2db2010-01-11 19:03:013643 for (int i = 0; i < kIterations; ++i) {
3644 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363645 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163646 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
3647 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193648 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013649
mmenkecbc2b712014-10-09 20:29:073650 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013651
[email protected]f7022f32014-08-21 16:32:193652 r->Start();
3653 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013654
[email protected]255620da2013-08-19 13:14:293655 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013656
maksim.sisovb53724b52016-09-16 05:30:503657 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
3658 << d.request_status();
[email protected]762d2db2010-01-11 19:03:013659
3660 EXPECT_FALSE(d.received_data_before_response());
3661 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013662 }
3663 delete[] uploadBytes;
3664 }
3665
[email protected]ede03212012-09-07 12:52:263666 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343667 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363668 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553669 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363670 base::IntToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:163671 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:343672
[email protected]f7022f32014-08-21 16:32:193673 r->Start();
3674 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343675
[email protected]255620da2013-08-19 13:14:293676 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343677
maksim.sisovb53724b52016-09-16 05:30:503678 if (d.request_status() != OK) {
3679 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
3680 return false;
3681 }
[email protected]263163f2012-06-14 22:40:343682
maksim.sisovb53724b52016-09-16 05:30:503683 return true;
[email protected]263163f2012-06-14 22:40:343684 }
3685
tommycli59a63432015-11-06 00:10:553686 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503687
tommycli59a63432015-11-06 00:10:553688 private:
[email protected]1700c6a2012-02-22 18:07:073689 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353690};
3691
tommycli59a63432015-11-06 00:10:553692namespace {
3693
danakj8522a25b2016-04-16 00:17:363694std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:553695 const test_server::HttpRequest& request) {
3696 if (request.headers.find("Host") == request.headers.end() ||
3697 request.headers.at("Host") != "www.redirect.com" ||
3698 request.method != test_server::METHOD_CONNECT) {
3699 return nullptr;
3700 }
3701
danakj8522a25b2016-04-16 00:17:363702 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:553703 new test_server::BasicHttpResponse);
3704 http_response->set_code(HTTP_FOUND);
3705 http_response->AddCustomHeader("Location",
3706 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:483707 return std::move(http_response);
tommycli59a63432015-11-06 00:10:553708}
3709
3710} // namespace
3711
nharperb7441ef2016-01-25 23:54:143712class TestSSLConfigService : public SSLConfigService {
3713 public:
3714 TestSSLConfigService(bool ev_enabled,
3715 bool online_rev_checking,
3716 bool rev_checking_required_local_anchors,
3717 bool token_binding_enabled)
3718 : ev_enabled_(ev_enabled),
3719 online_rev_checking_(online_rev_checking),
3720 rev_checking_required_local_anchors_(
3721 rev_checking_required_local_anchors),
3722 token_binding_enabled_(token_binding_enabled),
davidben095ebb52017-04-12 22:23:343723 min_version_(kDefaultSSLVersionMin),
3724 max_version_(kDefaultSSLVersionMax) {}
nharperb7441ef2016-01-25 23:54:143725
davidben095ebb52017-04-12 22:23:343726 void set_max_version(uint16_t version) { max_version_ = version; }
nharperb7441ef2016-01-25 23:54:143727 void set_min_version(uint16_t version) { min_version_ = version; }
3728
nharperb7441ef2016-01-25 23:54:143729 // SSLConfigService:
3730 void GetSSLConfig(SSLConfig* config) override {
3731 *config = SSLConfig();
3732 config->rev_checking_enabled = online_rev_checking_;
3733 config->verify_ev_cert = ev_enabled_;
3734 config->rev_checking_required_local_anchors =
3735 rev_checking_required_local_anchors_;
davidben095ebb52017-04-12 22:23:343736 config->version_min = min_version_;
3737 config->version_max = max_version_;
nharperb7441ef2016-01-25 23:54:143738 if (token_binding_enabled_) {
3739 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
3740 }
3741 }
3742
3743 protected:
3744 ~TestSSLConfigService() override {}
3745
3746 private:
3747 const bool ev_enabled_;
3748 const bool online_rev_checking_;
3749 const bool rev_checking_required_local_anchors_;
3750 const bool token_binding_enabled_;
3751 uint16_t min_version_;
davidben095ebb52017-04-12 22:23:343752 uint16_t max_version_;
nharperb7441ef2016-01-25 23:54:143753};
3754
3755// TODO(svaldez): Update tests to use EmbeddedTestServer.
3756#if !defined(OS_IOS)
3757class TokenBindingURLRequestTest : public URLRequestTestHTTP {
3758 public:
fdoray9f0b4782017-02-10 12:55:473759 TokenBindingURLRequestTest() = default;
fdoraya89e673c2017-01-31 21:44:213760
nharperb7441ef2016-01-25 23:54:143761 void SetUp() override {
3762 default_context_.set_ssl_config_service(
3763 new TestSSLConfigService(false, false, false, true));
fdoraya89e673c2017-01-31 21:44:213764 channel_id_service_.reset(
3765 new ChannelIDService(new DefaultChannelIDStore(NULL)));
nharperb7441ef2016-01-25 23:54:143766 default_context_.set_channel_id_service(channel_id_service_.get());
3767 URLRequestTestHTTP::SetUp();
3768 }
3769
3770 protected:
danakj8522a25b2016-04-16 00:17:363771 std::unique_ptr<ChannelIDService> channel_id_service_;
nharperb7441ef2016-01-25 23:54:143772};
3773
3774TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
3775 SpawnedTestServer::SSLOptions ssl_options;
3776 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3777 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3778 ssl_options,
3779 base::FilePath(kTestFilePath));
3780 ASSERT_TRUE(https_test_server.Start());
3781
3782 TestDelegate d;
3783 {
danakj8522a25b2016-04-16 00:17:363784 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163785 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d,
3786 TRAFFIC_ANNOTATION_FOR_TESTS));
nharperb7441ef2016-01-25 23:54:143787 r->Start();
3788 EXPECT_TRUE(r->is_pending());
3789
3790 base::RunLoop().Run();
3791
maksim.sisovb53724b52016-09-16 05:30:503792 EXPECT_EQ(OK, d.request_status());
nharperb7441ef2016-01-25 23:54:143793
3794 HttpRequestHeaders headers;
3795 std::string token_binding_header, token_binding_message;
3796 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3797 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3798 &token_binding_header));
3799 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353800 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperb7441ef2016-01-25 23:54:143801 &token_binding_message));
nharperd6e65822016-03-30 23:05:483802 std::vector<TokenBinding> token_bindings;
3803 ASSERT_TRUE(
3804 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3805 ASSERT_EQ(1ull, token_bindings.size());
nharperb7441ef2016-01-25 23:54:143806
3807 EXPECT_GT(d.bytes_received(), 0);
3808 std::string ekm = d.data_received();
3809
nharperd6e65822016-03-30 23:05:483810 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353811 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3812 token_bindings[0].signature,
3813 TokenBindingType::PROVIDED, ekm));
nharperb7441ef2016-01-25 23:54:143814 }
3815}
nharperd6e65822016-03-30 23:05:483816
3817TEST_F(TokenBindingURLRequestTest, ForwardTokenBinding) {
3818 SpawnedTestServer::SSLOptions ssl_options;
3819 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3820 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3821 ssl_options,
3822 base::FilePath(kTestFilePath));
3823 ASSERT_TRUE(https_test_server.Start());
3824
3825 TestDelegate d;
3826 {
3827 GURL redirect_url =
3828 https_test_server.GetURL("forward-tokbind?/tokbind-ekm");
rhalavatib7bd7c792017-04-27 05:25:163829 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3830 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:483831 r->Start();
3832 EXPECT_TRUE(r->is_pending());
3833
3834 base::RunLoop().Run();
3835
maksim.sisovb53724b52016-09-16 05:30:503836 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483837
3838 HttpRequestHeaders headers;
3839 std::string token_binding_header, token_binding_message;
3840 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3841 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3842 &token_binding_header));
3843 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353844 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483845 &token_binding_message));
3846 std::vector<TokenBinding> token_bindings;
3847 ASSERT_TRUE(
3848 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3849 ASSERT_EQ(2ull, token_bindings.size());
3850
3851 EXPECT_GT(d.bytes_received(), 0);
3852 std::string ekm = d.data_received();
3853
3854 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353855 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3856 token_bindings[0].signature,
3857 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483858 EXPECT_EQ(TokenBindingType::REFERRED, token_bindings[1].type);
nharper78e6d2b2016-09-21 05:42:353859 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[1].ec_point,
3860 token_bindings[1].signature,
3861 TokenBindingType::REFERRED, ekm));
nharperd6e65822016-03-30 23:05:483862 }
3863}
3864
3865// TODO(nharper): Remove this #ifdef and replace SpawnedTestServer with
3866// EmbeddedTestServer once crbug.com/599187 is resolved.
3867#if !defined(OS_ANDROID)
3868TEST_F(TokenBindingURLRequestTest, DontForwardHeaderFromHttp) {
Sergey Ulanov9e8d6f32017-08-14 22:12:583869 SpawnedTestServer http_server(SpawnedTestServer::TYPE_HTTP, base::FilePath());
nharperd6e65822016-03-30 23:05:483870 ASSERT_TRUE(http_server.Start());
3871 SpawnedTestServer::SSLOptions ssl_options;
3872 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3873 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3874 ssl_options,
3875 base::FilePath(kTestFilePath));
3876 ASSERT_TRUE(https_test_server.Start());
3877
3878 TestDelegate d;
3879 {
3880 GURL redirect_url = http_server.GetURL(
3881 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
rhalavatib7bd7c792017-04-27 05:25:163882 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3883 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:483884 r->Start();
3885 EXPECT_TRUE(r->is_pending());
3886
3887 base::RunLoop().Run();
3888
maksim.sisovb53724b52016-09-16 05:30:503889 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483890
3891 HttpRequestHeaders headers;
3892 std::string token_binding_header, token_binding_message;
3893 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3894 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3895 &token_binding_header));
3896 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353897 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483898 &token_binding_message));
3899 std::vector<TokenBinding> token_bindings;
3900 ASSERT_TRUE(
3901 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3902 ASSERT_EQ(1ull, token_bindings.size());
3903
3904 EXPECT_GT(d.bytes_received(), 0);
3905 std::string ekm = d.data_received();
3906
3907 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353908 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3909 token_bindings[0].signature,
3910 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483911 }
3912}
3913
3914// Test that if a server supporting Token Binding redirects (with
nharper86f0be22016-07-14 00:49:363915// Include-Referred-Token-Binding-ID) to an https url on a server that does not
nharperd6e65822016-03-30 23:05:483916// support Token Binding, then we do not send a Sec-Token-Binding when following
3917// the redirect.
3918TEST_F(TokenBindingURLRequestTest, ForwardWithoutTokenBinding) {
3919 SpawnedTestServer::SSLOptions ssl_options;
3920 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3921 ssl_options,
3922 base::FilePath(kTestFilePath));
3923 ASSERT_TRUE(https_test_server.Start());
3924 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3925 SpawnedTestServer token_binding_test_server(SpawnedTestServer::TYPE_HTTPS,
3926 ssl_options,
3927 base::FilePath(kTestFilePath));
3928 ASSERT_TRUE(token_binding_test_server.Start());
3929
3930 TestDelegate d;
3931 {
3932 GURL redirect_url = token_binding_test_server.GetURL(
3933 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
rhalavatib7bd7c792017-04-27 05:25:163934 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3935 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:483936 r->Start();
3937 EXPECT_TRUE(r->is_pending());
3938
3939 base::RunLoop().Run();
3940
maksim.sisovb53724b52016-09-16 05:30:503941 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483942
3943 HttpRequestHeaders headers;
3944 std::string token_binding_header, token_binding_message;
3945 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3946 EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3947 &token_binding_header));
3948 }
3949}
3950#endif // !defined(OS_ANDROID)
nharperb7441ef2016-01-25 23:54:143951#endif // !defined(OS_IOS)
3952
3953// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113954// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553955// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113956// follow.
[email protected]f2f31b32013-01-16 23:24:093957TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553958 http_test_server()->RegisterRequestHandler(
3959 base::Bind(&HandleRedirectConnect));
3960 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113961
[email protected]ceefd7fd2012-11-29 00:36:243962 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043963 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553964 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503965
[email protected]d1ec59082009-02-11 02:48:153966 TestDelegate d;
3967 {
danakj8522a25b2016-04-16 00:17:363968 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163969 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
3970 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193971 r->Start();
3972 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153973
[email protected]255620da2013-08-19 13:14:293974 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153975
[email protected]d8fc4722014-06-13 13:17:153976 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:473977 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:503978 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:083979 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153980 // We should not have followed the redirect.
3981 EXPECT_EQ(0, d.received_redirect_count());
3982 }
3983}
3984
[email protected]8202d0c2011-02-23 08:31:143985// This is the same as the previous test, but checks that the network delegate
3986// registers the error.
[email protected]c044616e2013-02-20 02:01:263987TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553988 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143989
[email protected]ceefd7fd2012-11-29 00:36:243990 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043991 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553992 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503993
[email protected]8202d0c2011-02-23 08:31:143994 TestDelegate d;
3995 {
danakj8522a25b2016-04-16 00:17:363996 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163997 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
3998 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193999 r->Start();
4000 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144001
[email protected]255620da2013-08-19 13:14:294002 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:144003
[email protected]d8fc4722014-06-13 13:17:154004 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474005 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:144006 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504007 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144008 // We should not have followed the redirect.
4009 EXPECT_EQ(0, d.received_redirect_count());
4010
4011 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014012 EXPECT_THAT(network_delegate.last_error(),
4013 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144014 }
4015}
4016
[email protected]dc5a5cf2012-09-26 02:49:304017// Tests that we can block and asynchronously return OK in various stages.
4018TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4019 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4020 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4021 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4022 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4023 };
4024 static const size_t blocking_stages_length = arraysize(blocking_stages);
4025
tommycli59a63432015-11-06 00:10:554026 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304027
4028 TestDelegate d;
4029 BlockingNetworkDelegate network_delegate(
4030 BlockingNetworkDelegate::USER_CALLBACK);
4031 network_delegate.set_block_on(
4032 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4033 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4034 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4035
4036 TestURLRequestContext context(true);
4037 context.set_network_delegate(&network_delegate);
4038 context.Init();
4039
4040 {
danakj8522a25b2016-04-16 00:17:364041 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164042 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4043 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304044
[email protected]f7022f32014-08-21 16:32:194045 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304046 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:294047 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304048 EXPECT_EQ(blocking_stages[i],
4049 network_delegate.stage_blocked_for_callback());
4050 network_delegate.DoCallback(OK);
4051 }
[email protected]255620da2013-08-19 13:14:294052 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194053 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504054 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304055 EXPECT_EQ(1, network_delegate.created_requests());
4056 EXPECT_EQ(0, network_delegate.destroyed_requests());
4057 }
4058 EXPECT_EQ(1, network_delegate.destroyed_requests());
4059}
4060
[email protected]4c76d7c2011-04-15 19:14:124061// Tests that the network delegate can block and cancel a request.
4062TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554063 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124064
4065 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304066 BlockingNetworkDelegate network_delegate(
4067 BlockingNetworkDelegate::AUTO_CALLBACK);
4068 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4069 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124070
[email protected]d5a4dd62012-05-23 01:41:044071 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554072 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504073
[email protected]4c76d7c2011-04-15 19:14:124074 {
rhalavatib7bd7c792017-04-27 05:25:164075 std::unique_ptr<URLRequest> r(
4076 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4077 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124078
[email protected]f7022f32014-08-21 16:32:194079 r->Start();
[email protected]255620da2013-08-19 13:14:294080 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:124081
[email protected]d8fc4722014-06-13 13:17:154082 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474083 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504084 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124085 EXPECT_EQ(1, network_delegate.created_requests());
4086 EXPECT_EQ(0, network_delegate.destroyed_requests());
4087 }
4088 EXPECT_EQ(1, network_delegate.destroyed_requests());
4089}
4090
[email protected]b4438d32012-09-27 06:15:304091// Helper function for NetworkDelegateCancelRequestAsynchronously and
4092// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4093// delegate operating in |block_mode| and a request for |url|. It blocks the
4094// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4095void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4096 BlockingNetworkDelegate::Stage stage,
4097 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364098 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304099 BlockingNetworkDelegate network_delegate(block_mode);
4100 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4101 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364102
[email protected]b4438d32012-09-27 06:15:304103 TestURLRequestContext context(true);
4104 context.set_network_delegate(&network_delegate);
4105 context.Init();
[email protected]3cd384c602011-08-31 16:12:364106
4107 {
rhalavatib7bd7c792017-04-27 05:25:164108 std::unique_ptr<URLRequest> r(context.CreateRequest(
4109 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364110
[email protected]f7022f32014-08-21 16:32:194111 r->Start();
[email protected]255620da2013-08-19 13:14:294112 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:364113
[email protected]d8fc4722014-06-13 13:17:154114 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474115 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4116 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4117 EXPECT_FALSE(r->proxy_server().is_valid());
4118 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4119 EXPECT_TRUE(r->proxy_server().is_direct());
4120 } else {
4121 NOTREACHED();
4122 }
maksim.sisovb53724b52016-09-16 05:30:504123 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364124 EXPECT_EQ(1, network_delegate.created_requests());
4125 EXPECT_EQ(0, network_delegate.destroyed_requests());
4126 }
4127 EXPECT_EQ(1, network_delegate.destroyed_requests());
4128}
4129
[email protected]b4438d32012-09-27 06:15:304130// The following 3 tests check that the network delegate can cancel a request
4131// synchronously in various stages of the request.
4132TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554133 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304134 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4135 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554136 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304137}
4138
4139TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554140 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304141 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4142 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554143 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304144}
4145
4146TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554147 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304148 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4149 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554150 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304151}
4152
4153// The following 3 tests check that the network delegate can cancel a request
4154// asynchronously in various stages of the request.
4155TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554156 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304157 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4158 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554159 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304160}
4161
4162TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554163 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304164 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4165 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554166 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304167}
4168
4169TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554170 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304171 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4172 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554173 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304174}
4175
[email protected]4c76d7c2011-04-15 19:14:124176// Tests that the network delegate can block and redirect a request to a new
4177// URL.
4178TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554179 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124180
4181 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304182 BlockingNetworkDelegate network_delegate(
4183 BlockingNetworkDelegate::AUTO_CALLBACK);
4184 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554185 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:124186 network_delegate.set_redirect_url(redirect_url);
4187
[email protected]d5a4dd62012-05-23 01:41:044188 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554189 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504190
[email protected]4c76d7c2011-04-15 19:14:124191 {
tommycli59a63432015-11-06 00:10:554192 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164193 std::unique_ptr<URLRequest> r(context.CreateRequest(
4194 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124195
[email protected]6be6fa92014-08-06 23:44:564196 // Quit after hitting the redirect, so can check the headers.
4197 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194198 r->Start();
[email protected]255620da2013-08-19 13:14:294199 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:124200
[email protected]6be6fa92014-08-06 23:44:564201 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194202 EXPECT_EQ(307, r->GetResponseCode());
4203 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564204 std::string location;
[email protected]f7022f32014-08-21 16:32:194205 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4206 &location));
[email protected]6be6fa92014-08-06 23:44:564207 EXPECT_EQ(redirect_url, GURL(location));
4208
4209 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194210 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564211 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:504212 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474213 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4214 http_test_server()->host_port_pair()),
4215 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094216 // before_send_headers_with_proxy_count only increments for headers sent
4217 // through an untunneled proxy.
4218 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554219 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4220 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274221
maksim.sisovb53724b52016-09-16 05:30:504222 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194223 EXPECT_EQ(redirect_url, r->url());
4224 EXPECT_EQ(original_url, r->original_url());
4225 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124226 EXPECT_EQ(1, network_delegate.created_requests());
4227 EXPECT_EQ(0, network_delegate.destroyed_requests());
4228 }
4229 EXPECT_EQ(1, network_delegate.destroyed_requests());
4230}
4231
[email protected]b813ed72012-04-05 08:21:364232// Tests that the network delegate can block and redirect a request to a new
4233// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4234TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554235 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364236
4237 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304238 BlockingNetworkDelegate network_delegate(
4239 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:554240 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:364241 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364242
[email protected]d5a4dd62012-05-23 01:41:044243 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554244 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364245
4246 {
tommycli59a63432015-11-06 00:10:554247 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164248 std::unique_ptr<URLRequest> r(context.CreateRequest(
4249 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364250
[email protected]6be6fa92014-08-06 23:44:564251 // Quit after hitting the redirect, so can check the headers.
4252 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194253 r->Start();
[email protected]255620da2013-08-19 13:14:294254 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:364255
[email protected]6be6fa92014-08-06 23:44:564256 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194257 EXPECT_EQ(307, r->GetResponseCode());
4258 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564259 std::string location;
[email protected]f7022f32014-08-21 16:32:194260 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4261 &location));
[email protected]6be6fa92014-08-06 23:44:564262 EXPECT_EQ(redirect_url, GURL(location));
4263
4264 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194265 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564266 base::RunLoop().Run();
4267
maksim.sisovb53724b52016-09-16 05:30:504268 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474269 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4270 http_test_server()->host_port_pair()),
4271 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094272 // before_send_headers_with_proxy_count only increments for headers sent
4273 // through an untunneled proxy.
4274 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554275 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4276 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504277 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194278 EXPECT_EQ(redirect_url, r->url());
4279 EXPECT_EQ(original_url, r->original_url());
4280 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364281 EXPECT_EQ(1, network_delegate.created_requests());
4282 EXPECT_EQ(0, network_delegate.destroyed_requests());
4283 }
4284 EXPECT_EQ(1, network_delegate.destroyed_requests());
4285}
4286
[email protected]3c5ca8c2011-09-29 01:14:514287// Tests that redirects caused by the network delegate preserve POST data.
4288TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554289 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514290
4291 const char kData[] = "hello world";
4292
4293 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304294 BlockingNetworkDelegate network_delegate(
4295 BlockingNetworkDelegate::AUTO_CALLBACK);
4296 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554297 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514298 network_delegate.set_redirect_url(redirect_url);
4299
[email protected]ef2bf422012-05-11 03:27:094300 TestURLRequestContext context(true);
4301 context.set_network_delegate(&network_delegate);
4302 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514303
4304 {
tommycli59a63432015-11-06 00:10:554305 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164306 std::unique_ptr<URLRequest> r(context.CreateRequest(
4307 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194308 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074309 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514310 HttpRequestHeaders headers;
4311 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:514312 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194313 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564314
4315 // Quit after hitting the redirect, so can check the headers.
4316 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194317 r->Start();
[email protected]255620da2013-08-19 13:14:294318 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:514319
[email protected]6be6fa92014-08-06 23:44:564320 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194321 EXPECT_EQ(307, r->GetResponseCode());
4322 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564323 std::string location;
[email protected]f7022f32014-08-21 16:32:194324 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4325 &location));
[email protected]6be6fa92014-08-06 23:44:564326 EXPECT_EQ(redirect_url, GURL(location));
4327
4328 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194329 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564330 base::RunLoop().Run();
4331
maksim.sisovb53724b52016-09-16 05:30:504332 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194333 EXPECT_EQ(redirect_url, r->url());
4334 EXPECT_EQ(original_url, r->original_url());
4335 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514336 EXPECT_EQ(1, network_delegate.created_requests());
4337 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194338 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514339 EXPECT_EQ(kData, d.data_received());
4340 }
4341 EXPECT_EQ(1, network_delegate.destroyed_requests());
4342}
4343
[email protected]5f714132014-03-26 10:41:164344// Tests that the network delegate can block and redirect a request to a new
4345// URL during OnHeadersReceived.
4346TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554347 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164348
4349 TestDelegate d;
4350 BlockingNetworkDelegate network_delegate(
4351 BlockingNetworkDelegate::AUTO_CALLBACK);
4352 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:554353 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:164354 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4355
4356 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554357 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164358
4359 {
tommycli59a63432015-11-06 00:10:554360 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164361 std::unique_ptr<URLRequest> r(context.CreateRequest(
4362 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164363
[email protected]f7022f32014-08-21 16:32:194364 r->Start();
[email protected]5f714132014-03-26 10:41:164365 base::RunLoop().Run();
4366
maksim.sisovb53724b52016-09-16 05:30:504367 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474368 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4369 http_test_server()->host_port_pair()),
4370 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094371 // before_send_headers_with_proxy_count only increments for headers sent
4372 // through an untunneled proxy.
4373 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554374 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4375 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194376
maksim.sisovb53724b52016-09-16 05:30:504377 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194378 EXPECT_EQ(redirect_url, r->url());
4379 EXPECT_EQ(original_url, r->original_url());
4380 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164381 EXPECT_EQ(2, network_delegate.created_requests());
4382 EXPECT_EQ(0, network_delegate.destroyed_requests());
4383 }
4384 EXPECT_EQ(1, network_delegate.destroyed_requests());
4385}
4386
[email protected]c2911d72011-10-03 22:16:364387// Tests that the network delegate can synchronously complete OnAuthRequired
4388// by taking no action. This indicates that the NetworkDelegate does not want to
4389// handle the challenge, and is passing the buck along to the
4390// URLRequest::Delegate.
4391TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554392 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364393
4394 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304395 BlockingNetworkDelegate network_delegate(
4396 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364397
[email protected]ef2bf422012-05-11 03:27:094398 TestURLRequestContext context(true);
4399 context.set_network_delegate(&network_delegate);
4400 context.Init();
[email protected]c2911d72011-10-03 22:16:364401
[email protected]f3cf9802011-10-28 18:44:584402 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364403
4404 {
tommycli59a63432015-11-06 00:10:554405 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164406 std::unique_ptr<URLRequest> r(context.CreateRequest(
4407 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194408 r->Start();
[email protected]79e1fd62013-06-20 06:50:044409
[email protected]255620da2013-08-19 13:14:294410 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044411
maksim.sisovb53724b52016-09-16 05:30:504412 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194413 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044414 EXPECT_TRUE(d.auth_required_called());
4415 EXPECT_EQ(1, network_delegate.created_requests());
4416 EXPECT_EQ(0, network_delegate.destroyed_requests());
4417 }
4418 EXPECT_EQ(1, network_delegate.destroyed_requests());
4419}
4420
4421TEST_F(URLRequestTestHTTP,
4422 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554423 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044424
4425 TestDelegate d;
4426 BlockingNetworkDelegate network_delegate(
4427 BlockingNetworkDelegate::SYNCHRONOUS);
4428
4429 TestURLRequestContext context(true);
4430 context.set_network_delegate(&network_delegate);
4431 context.Init();
4432
4433 d.set_credentials(AuthCredentials(kUser, kSecret));
4434
4435 {
tommycli59a63432015-11-06 00:10:554436 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164437 std::unique_ptr<URLRequest> r(context.CreateRequest(
4438 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194439 r->Start();
[email protected]79e1fd62013-06-20 06:50:044440
shivanisha8061c4202017-06-13 23:35:524441 base::RunLoop().Run();
4442
[email protected]79e1fd62013-06-20 06:50:044443 {
4444 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194445 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524446 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044447 }
4448
maksim.sisovb53724b52016-09-16 05:30:504449 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194450 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364451 EXPECT_TRUE(d.auth_required_called());
4452 EXPECT_EQ(1, network_delegate.created_requests());
4453 EXPECT_EQ(0, network_delegate.destroyed_requests());
4454 }
4455 EXPECT_EQ(1, network_delegate.destroyed_requests());
4456}
4457
4458// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404459// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364460TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554461 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364462
4463 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304464 BlockingNetworkDelegate network_delegate(
4465 BlockingNetworkDelegate::SYNCHRONOUS);
4466 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364467 network_delegate.set_auth_retval(
4468 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4469
[email protected]f3cf9802011-10-28 18:44:584470 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364471
[email protected]ef2bf422012-05-11 03:27:094472 TestURLRequestContext context(true);
4473 context.set_network_delegate(&network_delegate);
4474 context.Init();
[email protected]c2911d72011-10-03 22:16:364475
4476 {
tommycli59a63432015-11-06 00:10:554477 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164478 std::unique_ptr<URLRequest> r(context.CreateRequest(
4479 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194480 r->Start();
[email protected]255620da2013-08-19 13:14:294481 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364482
maksim.sisovb53724b52016-09-16 05:30:504483 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194484 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364485 EXPECT_FALSE(d.auth_required_called());
4486 EXPECT_EQ(1, network_delegate.created_requests());
4487 EXPECT_EQ(0, network_delegate.destroyed_requests());
4488 }
4489 EXPECT_EQ(1, network_delegate.destroyed_requests());
4490}
4491
[email protected]79e1fd62013-06-20 06:50:044492// Same as above, but also tests that GetFullRequestHeaders returns the proper
4493// headers (for the first or second request) when called at the proper times.
4494TEST_F(URLRequestTestHTTP,
4495 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554496 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044497
4498 TestDelegate d;
4499 BlockingNetworkDelegate network_delegate(
4500 BlockingNetworkDelegate::SYNCHRONOUS);
4501 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4502 network_delegate.set_auth_retval(
4503 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4504
4505 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4506
4507 TestURLRequestContext context(true);
4508 context.set_network_delegate(&network_delegate);
4509 context.Init();
4510
4511 {
tommycli59a63432015-11-06 00:10:554512 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164513 std::unique_ptr<URLRequest> r(context.CreateRequest(
4514 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194515 r->Start();
[email protected]255620da2013-08-19 13:14:294516 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044517
maksim.sisovb53724b52016-09-16 05:30:504518 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194519 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044520 EXPECT_FALSE(d.auth_required_called());
4521 EXPECT_EQ(1, network_delegate.created_requests());
4522 EXPECT_EQ(0, network_delegate.destroyed_requests());
4523
4524 {
4525 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194526 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044527 EXPECT_TRUE(headers.HasHeader("Authorization"));
4528 }
4529 }
4530 EXPECT_EQ(1, network_delegate.destroyed_requests());
4531}
4532
[email protected]c2911d72011-10-03 22:16:364533// Tests that the network delegate can synchronously complete OnAuthRequired
4534// by cancelling authentication.
4535TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554536 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364537
4538 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304539 BlockingNetworkDelegate network_delegate(
4540 BlockingNetworkDelegate::SYNCHRONOUS);
4541 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364542 network_delegate.set_auth_retval(
4543 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4544
[email protected]ef2bf422012-05-11 03:27:094545 TestURLRequestContext context(true);
4546 context.set_network_delegate(&network_delegate);
4547 context.Init();
[email protected]c2911d72011-10-03 22:16:364548
4549 {
tommycli59a63432015-11-06 00:10:554550 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164551 std::unique_ptr<URLRequest> r(context.CreateRequest(
4552 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194553 r->Start();
[email protected]255620da2013-08-19 13:14:294554 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364555
maksim.sisovb53724b52016-09-16 05:30:504556 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194557 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364558 EXPECT_FALSE(d.auth_required_called());
4559 EXPECT_EQ(1, network_delegate.created_requests());
4560 EXPECT_EQ(0, network_delegate.destroyed_requests());
4561 }
4562 EXPECT_EQ(1, network_delegate.destroyed_requests());
4563}
4564
4565// Tests that the network delegate can asynchronously complete OnAuthRequired
4566// by taking no action. This indicates that the NetworkDelegate does not want
4567// to handle the challenge, and is passing the buck along to the
4568// URLRequest::Delegate.
4569TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554570 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364571
4572 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304573 BlockingNetworkDelegate network_delegate(
4574 BlockingNetworkDelegate::AUTO_CALLBACK);
4575 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364576
[email protected]ef2bf422012-05-11 03:27:094577 TestURLRequestContext context(true);
4578 context.set_network_delegate(&network_delegate);
4579 context.Init();
[email protected]c2911d72011-10-03 22:16:364580
[email protected]f3cf9802011-10-28 18:44:584581 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364582
4583 {
tommycli59a63432015-11-06 00:10:554584 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164585 std::unique_ptr<URLRequest> r(context.CreateRequest(
4586 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194587 r->Start();
[email protected]255620da2013-08-19 13:14:294588 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364589
maksim.sisovb53724b52016-09-16 05:30:504590 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194591 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364592 EXPECT_TRUE(d.auth_required_called());
4593 EXPECT_EQ(1, network_delegate.created_requests());
4594 EXPECT_EQ(0, network_delegate.destroyed_requests());
4595 }
4596 EXPECT_EQ(1, network_delegate.destroyed_requests());
4597}
4598
4599// Tests that the network delegate can asynchronously complete OnAuthRequired
4600// by setting credentials.
4601TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554602 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364603
4604 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304605 BlockingNetworkDelegate network_delegate(
4606 BlockingNetworkDelegate::AUTO_CALLBACK);
4607 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364608 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364609 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4610
[email protected]f3cf9802011-10-28 18:44:584611 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364612 network_delegate.set_auth_credentials(auth_credentials);
4613
[email protected]ef2bf422012-05-11 03:27:094614 TestURLRequestContext context(true);
4615 context.set_network_delegate(&network_delegate);
4616 context.Init();
[email protected]c2911d72011-10-03 22:16:364617
4618 {
tommycli59a63432015-11-06 00:10:554619 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164620 std::unique_ptr<URLRequest> r(context.CreateRequest(
4621 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194622 r->Start();
[email protected]255620da2013-08-19 13:14:294623 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364624
maksim.sisovb53724b52016-09-16 05:30:504625 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194626 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364627 EXPECT_FALSE(d.auth_required_called());
4628 EXPECT_EQ(1, network_delegate.created_requests());
4629 EXPECT_EQ(0, network_delegate.destroyed_requests());
4630 }
4631 EXPECT_EQ(1, network_delegate.destroyed_requests());
4632}
4633
4634// Tests that the network delegate can asynchronously complete OnAuthRequired
4635// by cancelling authentication.
4636TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554637 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364638
4639 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304640 BlockingNetworkDelegate network_delegate(
4641 BlockingNetworkDelegate::AUTO_CALLBACK);
4642 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364643 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364644 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4645
[email protected]ef2bf422012-05-11 03:27:094646 TestURLRequestContext context(true);
4647 context.set_network_delegate(&network_delegate);
4648 context.Init();
[email protected]c2911d72011-10-03 22:16:364649
4650 {
tommycli59a63432015-11-06 00:10:554651 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164652 std::unique_ptr<URLRequest> r(context.CreateRequest(
4653 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194654 r->Start();
[email protected]255620da2013-08-19 13:14:294655 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364656
maksim.sisovb53724b52016-09-16 05:30:504657 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194658 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364659 EXPECT_FALSE(d.auth_required_called());
4660 EXPECT_EQ(1, network_delegate.created_requests());
4661 EXPECT_EQ(0, network_delegate.destroyed_requests());
4662 }
4663 EXPECT_EQ(1, network_delegate.destroyed_requests());
4664}
4665
[email protected]9045b8822012-01-13 20:35:354666// Tests that we can handle when a network request was canceled while we were
4667// waiting for the network delegate.
4668// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4669TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554670 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354671
4672 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304673 BlockingNetworkDelegate network_delegate(
4674 BlockingNetworkDelegate::USER_CALLBACK);
4675 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354676
[email protected]ef2bf422012-05-11 03:27:094677 TestURLRequestContext context(true);
4678 context.set_network_delegate(&network_delegate);
4679 context.Init();
[email protected]9045b8822012-01-13 20:35:354680
4681 {
rhalavatib7bd7c792017-04-27 05:25:164682 std::unique_ptr<URLRequest> r(
4683 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4684 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354685
[email protected]f7022f32014-08-21 16:32:194686 r->Start();
[email protected]255620da2013-08-19 13:14:294687 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304688 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4689 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354690 EXPECT_EQ(0, network_delegate.completed_requests());
4691 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194692 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354693 // Ensure that network delegate is notified.
4694 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504695 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354696 EXPECT_EQ(1, network_delegate.created_requests());
4697 EXPECT_EQ(0, network_delegate.destroyed_requests());
4698 }
4699 EXPECT_EQ(1, network_delegate.destroyed_requests());
4700}
4701
4702// Tests that we can handle when a network request was canceled while we were
4703// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:004704// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
4705// callback.
[email protected]9045b8822012-01-13 20:35:354706TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554707 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354708
4709 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304710 BlockingNetworkDelegate network_delegate(
4711 BlockingNetworkDelegate::USER_CALLBACK);
4712 network_delegate.set_block_on(
4713 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354714
[email protected]ef2bf422012-05-11 03:27:094715 TestURLRequestContext context(true);
4716 context.set_network_delegate(&network_delegate);
4717 context.Init();
[email protected]9045b8822012-01-13 20:35:354718
4719 {
rhalavatib7bd7c792017-04-27 05:25:164720 std::unique_ptr<URLRequest> r(
4721 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4722 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354723
[email protected]f7022f32014-08-21 16:32:194724 r->Start();
[email protected]255620da2013-08-19 13:14:294725 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304726 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4727 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354728 EXPECT_EQ(0, network_delegate.completed_requests());
4729 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194730 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354731 // Ensure that network delegate is notified.
4732 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504733 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354734 EXPECT_EQ(1, network_delegate.created_requests());
4735 EXPECT_EQ(0, network_delegate.destroyed_requests());
4736 }
4737 EXPECT_EQ(1, network_delegate.destroyed_requests());
4738}
4739
4740// Tests that we can handle when a network request was canceled while we were
4741// waiting for the network delegate.
4742// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4743TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554744 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354745
4746 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304747 BlockingNetworkDelegate network_delegate(
4748 BlockingNetworkDelegate::USER_CALLBACK);
4749 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354750
[email protected]ef2bf422012-05-11 03:27:094751 TestURLRequestContext context(true);
4752 context.set_network_delegate(&network_delegate);
4753 context.Init();
[email protected]9045b8822012-01-13 20:35:354754
4755 {
rhalavatib7bd7c792017-04-27 05:25:164756 std::unique_ptr<URLRequest> r(
4757 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4758 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354759
[email protected]f7022f32014-08-21 16:32:194760 r->Start();
[email protected]255620da2013-08-19 13:14:294761 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304762 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4763 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354764 EXPECT_EQ(0, network_delegate.completed_requests());
4765 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194766 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354767 // Ensure that network delegate is notified.
4768 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504769 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354770 EXPECT_EQ(1, network_delegate.created_requests());
4771 EXPECT_EQ(0, network_delegate.destroyed_requests());
4772 }
4773 EXPECT_EQ(1, network_delegate.destroyed_requests());
4774}
4775
4776// Tests that we can handle when a network request was canceled while we were
4777// waiting for the network delegate.
4778// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024779TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554780 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354781
4782 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304783 BlockingNetworkDelegate network_delegate(
4784 BlockingNetworkDelegate::USER_CALLBACK);
4785 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354786
[email protected]ef2bf422012-05-11 03:27:094787 TestURLRequestContext context(true);
4788 context.set_network_delegate(&network_delegate);
4789 context.Init();
[email protected]9045b8822012-01-13 20:35:354790
4791 {
danakj8522a25b2016-04-16 00:17:364792 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164793 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
4794 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354795
[email protected]f7022f32014-08-21 16:32:194796 r->Start();
[email protected]255620da2013-08-19 13:14:294797 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304798 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4799 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354800 EXPECT_EQ(0, network_delegate.completed_requests());
4801 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194802 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354803 // Ensure that network delegate is notified.
4804 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504805 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354806 EXPECT_EQ(1, network_delegate.created_requests());
4807 EXPECT_EQ(0, network_delegate.destroyed_requests());
4808 }
4809 EXPECT_EQ(1, network_delegate.destroyed_requests());
4810}
4811
tommycli59a63432015-11-06 00:10:554812namespace {
4813
danakj8522a25b2016-04-16 00:17:364814std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:554815 const test_server::HttpRequest& request) {
4816 if (request.headers.find("Host") == request.headers.end() ||
4817 request.headers.at("Host") != "www.server-auth.com" ||
4818 request.method != test_server::METHOD_CONNECT) {
4819 return nullptr;
4820 }
4821
danakj8522a25b2016-04-16 00:17:364822 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554823 new test_server::BasicHttpResponse);
4824 http_response->set_code(HTTP_UNAUTHORIZED);
4825 http_response->AddCustomHeader("WWW-Authenticate",
4826 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:484827 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554828}
4829
4830} // namespace
4831
4832// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114833// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554834// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354835TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554836 http_test_server()->RegisterRequestHandler(
4837 base::Bind(&HandleServerAuthConnect));
4838 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114839
[email protected]ceefd7fd2012-11-29 00:36:244840 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044841 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554842 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504843
[email protected]dc651782009-02-14 01:45:084844 TestDelegate d;
4845 {
danakj8522a25b2016-04-16 00:17:364846 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164847 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
4848 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:084849
[email protected]f7022f32014-08-21 16:32:194850 r->Start();
4851 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084852
[email protected]255620da2013-08-19 13:14:294853 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084854
[email protected]d8fc4722014-06-13 13:17:154855 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474856 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504857 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084858 }
4859}
4860
[email protected]b89290212009-08-14 22:37:354861TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554862 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114863
initial.commit586acc5fe2008-07-26 22:42:524864 TestDelegate d;
4865 {
danakj8522a25b2016-04-16 00:17:364866 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164867 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4868 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:524869
[email protected]f7022f32014-08-21 16:32:194870 r->Start();
4871 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524872
[email protected]255620da2013-08-19 13:14:294873 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524874
4875 EXPECT_EQ(1, d.response_started_count());
4876 EXPECT_FALSE(d.received_data_before_response());
4877 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554878 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194879 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554880 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194881 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164882
[email protected]9e743cd2010-03-16 07:03:534883 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524884 }
initial.commit586acc5fe2008-07-26 22:42:524885}
4886
[email protected]263163f2012-06-14 22:40:344887// This test has the server send a large number of cookies to the client.
4888// To ensure that no number of cookies causes a crash, a galloping binary
4889// search is used to estimate that maximum number of cookies that are accepted
4890// by the browser. Beyond the maximum number, the request will fail with
4891// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304892#if defined(OS_WIN)
4893// http://crbug.com/177916
4894#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4895#else
4896#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4897#endif // defined(OS_WIN)
4898TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554899 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344900
4901 int lower_bound = 0;
4902 int upper_bound = 1;
4903
4904 // Double the number of cookies until the response header limits are
4905 // exceeded.
4906 while (DoManyCookiesRequest(upper_bound)) {
4907 lower_bound = upper_bound;
4908 upper_bound *= 2;
4909 ASSERT_LT(upper_bound, 1000000);
4910 }
4911
pkasting6b68a162014-12-01 22:10:294912 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344913 if (tolerance < 2)
4914 tolerance = 2;
4915
4916 // Perform a binary search to find the highest possible number of cookies,
4917 // within the desired tolerance.
4918 while (upper_bound - lower_bound >= tolerance) {
4919 int num_cookies = (lower_bound + upper_bound) / 2;
4920
4921 if (DoManyCookiesRequest(num_cookies))
4922 lower_bound = num_cookies;
4923 else
4924 upper_bound = num_cookies;
4925 }
4926 // Success: the test did not crash.
4927}
4928
[email protected]b89290212009-08-14 22:37:354929TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554930 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114931
initial.commit586acc5fe2008-07-26 22:42:524932 TestDelegate d;
4933 {
danakj8522a25b2016-04-16 00:17:364934 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164935 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4936 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:524937
[email protected]f7022f32014-08-21 16:32:194938 r->Start();
4939 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524940
[email protected]255620da2013-08-19 13:14:294941 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524942
4943 EXPECT_EQ(1, d.response_started_count());
4944 EXPECT_FALSE(d.received_data_before_response());
4945 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554946 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194947 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554948 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194949 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524950 }
[email protected]5d7b373e2009-09-02 07:19:034951}
4952
[email protected]79e1fd62013-06-20 06:50:044953TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554954 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044955
4956 TestDelegate d;
4957 {
tommycli59a63432015-11-06 00:10:554958 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164959 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
4960 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:044961
4962 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194963 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044964
[email protected]f7022f32014-08-21 16:32:194965 r->Start();
4966 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044967
[email protected]255620da2013-08-19 13:14:294968 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044969
4970 EXPECT_EQ(1, d.response_started_count());
4971 EXPECT_FALSE(d.received_data_before_response());
4972 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554973 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194974 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554975 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194976 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044977
4978 EXPECT_TRUE(d.have_full_request_headers());
4979 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4980 }
4981}
4982
[email protected]58e32bb2013-01-21 18:23:254983TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554984 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254985
4986 TestDelegate d;
4987 {
danakj8522a25b2016-04-16 00:17:364988 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164989 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4990 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:254991
[email protected]f7022f32014-08-21 16:32:194992 r->Start();
4993 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254994
[email protected]255620da2013-08-19 13:14:294995 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254996
4997 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194998 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254999 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5000
5001 EXPECT_EQ(1, d.response_started_count());
5002 EXPECT_FALSE(d.received_data_before_response());
5003 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555004 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195005 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555006 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195007 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:255008 }
5009}
5010
tommycli59a63432015-11-06 00:10:555011// TODO(svaldez): Update tests to use EmbeddedTestServer.
5012#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395013TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555014 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555015 base::FilePath(kTestFilePath));
5016
5017 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395018
5019 // Parameter that specifies the Content-Length field in the response:
5020 // C - Compressed length.
5021 // U - Uncompressed length.
5022 // L - Large length (larger than both C & U).
5023 // M - Medium length (between C & U).
5024 // S - Small length (smaller than both C & U).
5025 const char test_parameters[] = "CULMS";
5026 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
5027 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445028 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395029 // S has too little data, but we seem to accept it.
5030 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375031 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395032
xunjielifb4da222016-07-14 18:38:595033 base::FilePath file_path;
5034 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
5035 file_path = file_path.Append(kTestFilePath);
5036 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5037 std::string expected_content;
5038 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5039
5040 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395041 TestDelegate d;
5042 {
tommycli59a63432015-11-06 00:10:555043 std::string test_file = base::StringPrintf(
5044 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395045
[email protected]ceefd7fd2012-11-29 00:36:245046 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095047 TestURLRequestContext context(true);
5048 context.set_network_delegate(&network_delegate);
5049 context.Init();
[email protected]87a09a92011-07-14 15:50:505050
rhalavatib7bd7c792017-04-27 05:25:165051 std::unique_ptr<URLRequest> r(
5052 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5053 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195054 r->Start();
5055 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395056
[email protected]255620da2013-08-19 13:14:295057 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:395058
5059 EXPECT_EQ(1, d.response_started_count());
5060 EXPECT_FALSE(d.received_data_before_response());
5061 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505062 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395063 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505064 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5065 << "\"";
xunjielifb4da222016-07-14 18:38:595066 if (test_parameters[i] == 'S') {
5067 // When content length is smaller than both compressed length and
5068 // uncompressed length, HttpStreamParser might not read the full
5069 // response body.
5070 continue;
5071 }
5072 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395073 } else {
maksim.sisovb53724b52016-09-16 05:30:505074 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395075 << " Parameter = \"" << test_file << "\"";
5076 }
5077 }
5078 }
5079}
tommycli59a63432015-11-06 00:10:555080#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395081
[email protected]58e32bb2013-01-21 18:23:255082TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555083 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255084
tommycli59a63432015-11-06 00:10:555085 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455086 GURL original_url =
tommycli59a63432015-11-06 00:10:555087 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255088 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165089 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5090 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195091 req->Start();
[email protected]255620da2013-08-19 13:14:295092 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255093
5094 EXPECT_EQ(1, d.response_started_count());
5095 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195096 EXPECT_EQ(destination_url, req->url());
5097 EXPECT_EQ(original_url, req->original_url());
5098 ASSERT_EQ(2U, req->url_chain().size());
5099 EXPECT_EQ(original_url, req->url_chain()[0]);
5100 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255101
5102 LoadTimingInfo load_timing_info_before_redirect;
5103 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5104 &load_timing_info_before_redirect));
5105 TestLoadTimingNotReused(load_timing_info_before_redirect,
5106 CONNECT_TIMING_HAS_DNS_TIMES);
5107
5108 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195109 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255110 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5111
5112 // Check that a new socket was used on redirect, since the server does not
5113 // supposed keep-alive sockets, and that the times before the redirect are
5114 // before the ones recorded for the second request.
5115 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5116 load_timing_info.socket_log_id);
5117 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5118 load_timing_info.connect_timing.connect_start);
5119}
5120
[email protected]8f1ac082011-04-19 21:14:135121TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555122 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135123
tommycli59a63432015-11-06 00:10:555124 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455125 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555126 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5127 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5128 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135129 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165130 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5131 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195132 req->Start();
[email protected]255620da2013-08-19 13:14:295133 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:135134
5135 EXPECT_EQ(1, d.response_started_count());
5136 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195137 EXPECT_EQ(destination_url, req->url());
5138 EXPECT_EQ(original_url, req->original_url());
5139 ASSERT_EQ(3U, req->url_chain().size());
5140 EXPECT_EQ(original_url, req->url_chain()[0]);
5141 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5142 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135143}
5144
[email protected]abe1c4a2013-10-25 19:28:515145// First and second pieces of information logged by delegates to URLRequests.
5146const char kFirstDelegateInfo[] = "Wonderful delegate";
5147const char kSecondDelegateInfo[] = "Exciting delegate";
5148
5149// Logs delegate information to a URLRequest. The first string is logged
5150// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5151// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5152// another asynchronous call is used to clear the delegate information
5153// before calling a callback. The object then deletes itself.
5154class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5155 public:
5156 typedef base::Callback<void()> Callback;
5157
5158 // Each time delegate information is added to the URLRequest, the resulting
5159 // load state is checked. The expected load state after each request is
5160 // passed in as an argument.
5161 static void Run(URLRequest* url_request,
5162 LoadState expected_first_load_state,
5163 LoadState expected_second_load_state,
5164 LoadState expected_third_load_state,
5165 const Callback& callback) {
5166 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
5167 url_request,
5168 expected_first_load_state,
5169 expected_second_load_state,
5170 expected_third_load_state,
5171 callback);
5172 logger->Start();
5173 }
5174
5175 // Checks that the log entries, starting with log_position, contain the
5176 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5177 // recorded. Returns the index of entry after the expected number of
5178 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:465179 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:515180 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515181 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5182 if (log_position + 3 >= entries.size()) {
5183 ADD_FAILURE() << "Not enough log entries";
5184 return entries.size();
5185 }
5186 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005187 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5188 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075189 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515190 &delegate_info));
5191 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
5192
5193 ++log_position;
mikecirone8b85c432016-09-08 19:11:005194 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5195 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515196
5197 ++log_position;
mikecirone8b85c432016-09-08 19:11:005198 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5199 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075200 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515201 &delegate_info));
5202 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
5203
5204 ++log_position;
mikecirone8b85c432016-09-08 19:11:005205 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5206 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515207
5208 return log_position + 1;
5209 }
5210
5211 private:
5212 friend class base::RefCounted<AsyncDelegateLogger>;
5213
5214 AsyncDelegateLogger(URLRequest* url_request,
5215 LoadState expected_first_load_state,
5216 LoadState expected_second_load_state,
5217 LoadState expected_third_load_state,
5218 const Callback& callback)
5219 : url_request_(url_request),
5220 expected_first_load_state_(expected_first_load_state),
5221 expected_second_load_state_(expected_second_load_state),
5222 expected_third_load_state_(expected_third_load_state),
5223 callback_(callback) {
5224 }
5225
5226 ~AsyncDelegateLogger() {}
5227
5228 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535229 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515230 LoadStateWithParam load_state = url_request_->GetLoadState();
5231 EXPECT_EQ(expected_first_load_state_, load_state.state);
5232 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455233 base::ThreadTaskRunnerHandle::Get()->PostTask(
5234 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515235 }
5236
5237 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535238 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515239 LoadStateWithParam load_state = url_request_->GetLoadState();
5240 EXPECT_EQ(expected_second_load_state_, load_state.state);
5241 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5242 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5243 } else {
5244 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5245 }
skyostil4891b25b2015-06-11 11:43:455246 base::ThreadTaskRunnerHandle::Get()->PostTask(
5247 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515248 }
5249
5250 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535251 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515252 LoadStateWithParam load_state = url_request_->GetLoadState();
5253 EXPECT_EQ(expected_third_load_state_, load_state.state);
5254 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085255 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515256 callback_.Run();
5257 }
5258
5259 URLRequest* url_request_;
5260 const int expected_first_load_state_;
5261 const int expected_second_load_state_;
5262 const int expected_third_load_state_;
5263 const Callback callback_;
5264
5265 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5266};
5267
5268// NetworkDelegate that logs delegate information before a request is started,
5269// before headers are sent, when headers are read, and when auth information
5270// is requested. Uses AsyncDelegateLogger.
5271class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5272 public:
5273 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:205274 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:515275
5276 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205277 int OnBeforeURLRequest(URLRequest* request,
5278 const CompletionCallback& callback,
5279 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:515280 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
5281 return RunCallbackAsynchronously(request, callback);
5282 }
5283
ryansturm2343cb62016-06-15 01:09:005284 int OnBeforeStartTransaction(URLRequest* request,
5285 const CompletionCallback& callback,
5286 HttpRequestHeaders* headers) override {
5287 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]abe1c4a2013-10-25 19:28:515288 return RunCallbackAsynchronously(request, callback);
5289 }
5290
dchengb03027d2014-10-21 12:00:205291 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515292 URLRequest* request,
5293 const CompletionCallback& callback,
5294 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165295 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135296 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:165297 TestNetworkDelegate::OnHeadersReceived(request,
5298 callback,
[email protected]abe1c4a2013-10-25 19:28:515299 original_response_headers,
[email protected]5f714132014-03-26 10:41:165300 override_response_headers,
5301 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:515302 return RunCallbackAsynchronously(request, callback);
5303 }
5304
dchengb03027d2014-10-21 12:00:205305 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515306 URLRequest* request,
5307 const AuthChallengeInfo& auth_info,
5308 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:135309 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515310 AsyncDelegateLogger::Run(
5311 request,
5312 LOAD_STATE_WAITING_FOR_DELEGATE,
5313 LOAD_STATE_WAITING_FOR_DELEGATE,
5314 LOAD_STATE_WAITING_FOR_DELEGATE,
5315 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5316 callback, credentials));
5317 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5318 }
5319
5320 private:
5321 static int RunCallbackAsynchronously(
5322 URLRequest* request,
5323 const CompletionCallback& callback) {
5324 AsyncDelegateLogger::Run(
5325 request,
5326 LOAD_STATE_WAITING_FOR_DELEGATE,
5327 LOAD_STATE_WAITING_FOR_DELEGATE,
5328 LOAD_STATE_WAITING_FOR_DELEGATE,
5329 base::Bind(callback, OK));
5330 return ERR_IO_PENDING;
5331 }
5332
5333 static void SetAuthAndResume(const AuthCallback& callback,
5334 AuthCredentials* credentials) {
5335 *credentials = AuthCredentials(kUser, kSecret);
5336 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
5337 }
5338
5339 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5340};
5341
5342// URLRequest::Delegate that logs delegate information when the headers
5343// are received, when each read completes, and during redirects. Uses
5344// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5345//
5346// Inherits from TestDelegate to reuse the TestDelegate code to handle
5347// advancing to the next step in most cases, as well as cancellation.
5348class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5349 public:
5350 enum CancelStage {
5351 NO_CANCEL = 0,
5352 CANCEL_ON_RECEIVED_REDIRECT,
5353 CANCEL_ON_RESPONSE_STARTED,
5354 CANCEL_ON_READ_COMPLETED
5355 };
5356
5357 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5358 : cancel_stage_(cancel_stage) {
5359 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5360 set_cancel_in_received_redirect(true);
5361 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5362 set_cancel_in_response_started(true);
5363 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5364 set_cancel_in_received_data(true);
5365 }
dchengb03027d2014-10-21 12:00:205366 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:515367
5368 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205369 void OnReceivedRedirect(URLRequest* request,
5370 const RedirectInfo& redirect_info,
5371 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515372 *defer_redirect = true;
5373 AsyncDelegateLogger::Run(
5374 request,
5375 LOAD_STATE_WAITING_FOR_DELEGATE,
5376 LOAD_STATE_WAITING_FOR_DELEGATE,
5377 LOAD_STATE_WAITING_FOR_DELEGATE,
5378 base::Bind(
5379 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595380 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515381 }
5382
maksim.sisov0f4aa142016-09-05 05:55:285383 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515384 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285385 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5386 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5387 base::Bind(
5388 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5389 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515390 }
5391
dchengb03027d2014-10-21 12:00:205392 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515393 AsyncDelegateLogger::Run(
5394 request,
5395 LOAD_STATE_IDLE,
5396 LOAD_STATE_IDLE,
5397 LOAD_STATE_IDLE,
5398 base::Bind(
5399 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5400 base::Unretained(this), request, bytes_read));
5401 }
5402
5403 private:
5404 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595405 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515406 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595407 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515408 // FollowDeferredRedirect should not be called after cancellation.
5409 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5410 return;
5411 if (!defer_redirect)
5412 request->FollowDeferredRedirect();
5413 }
5414
maksim.sisov0f4aa142016-09-05 05:55:285415 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515416 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285417 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515418 }
5419
5420 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5421 // The parent class continues the request.
5422 TestDelegate::OnReadCompleted(request, bytes_read);
5423 }
5424
5425 const CancelStage cancel_stage_;
5426
5427 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5428};
5429
5430// Tests handling of delegate info before a request starts.
5431TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555432 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515433
5434 TestDelegate request_delegate;
5435 TestURLRequestContext context(true);
5436 context.set_network_delegate(NULL);
5437 context.set_net_log(&net_log_);
5438 context.Init();
5439
5440 {
rhalavatib7bd7c792017-04-27 05:25:165441 std::unique_ptr<URLRequest> r(context.CreateRequest(
5442 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5443 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195444 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515445 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085446 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515447
5448 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195449 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515450 LOAD_STATE_WAITING_FOR_DELEGATE,
5451 LOAD_STATE_WAITING_FOR_DELEGATE,
5452 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195453 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515454
5455 base::RunLoop().Run();
5456
[email protected]f7022f32014-08-21 16:32:195457 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505458 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515459 }
5460
mmenke43758e62015-05-04 21:09:465461 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515462 net_log_.GetEntries(&entries);
5463 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005464 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515465
5466 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5467
5468 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005469 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5470 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515471}
5472
5473// Tests handling of delegate info from a network delegate.
5474TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555475 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515476
5477 TestDelegate request_delegate;
5478 AsyncLoggingNetworkDelegate network_delegate;
5479 TestURLRequestContext context(true);
5480 context.set_network_delegate(&network_delegate);
5481 context.set_net_log(&net_log_);
5482 context.Init();
5483
5484 {
rhalavatib7bd7c792017-04-27 05:25:165485 std::unique_ptr<URLRequest> r(context.CreateRequest(
5486 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
5487 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195488 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515489 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085490 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515491
[email protected]f7022f32014-08-21 16:32:195492 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515493 base::RunLoop().Run();
5494
[email protected]f7022f32014-08-21 16:32:195495 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505496 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515497 EXPECT_EQ(1, network_delegate.created_requests());
5498 EXPECT_EQ(0, network_delegate.destroyed_requests());
5499 }
5500 EXPECT_EQ(1, network_delegate.destroyed_requests());
5501
5502 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465503 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515504 net_log_.GetEntries(&entries);
5505 for (size_t i = 0; i < 3; ++i) {
5506 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005507 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5508 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515509
5510 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5511 log_position + 1);
5512
5513 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005514 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5515 entries[log_position].type);
5516 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515517 }
5518
mikecirone8b85c432016-09-08 19:11:005519 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5520 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515521}
5522
5523// Tests handling of delegate info from a network delegate in the case of an
5524// HTTP redirect.
5525TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555526 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515527
5528 TestDelegate request_delegate;
5529 AsyncLoggingNetworkDelegate network_delegate;
5530 TestURLRequestContext context(true);
5531 context.set_network_delegate(&network_delegate);
5532 context.set_net_log(&net_log_);
5533 context.Init();
5534
5535 {
danakj8522a25b2016-04-16 00:17:365536 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555537 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165538 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195539 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515540 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085541 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515542
[email protected]f7022f32014-08-21 16:32:195543 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515544 base::RunLoop().Run();
5545
[email protected]f7022f32014-08-21 16:32:195546 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505547 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515548 EXPECT_EQ(2, network_delegate.created_requests());
5549 EXPECT_EQ(0, network_delegate.destroyed_requests());
5550 }
5551 EXPECT_EQ(1, network_delegate.destroyed_requests());
5552
5553 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465554 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515555 net_log_.GetEntries(&entries);
5556 // The NetworkDelegate logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005557 // OnBeforeStartTransaction, and OnHeadersReceived.
[email protected]abe1c4a2013-10-25 19:28:515558 for (size_t i = 0; i < 3; ++i) {
5559 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005560 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5561 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515562
5563 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5564 log_position + 1);
5565
5566 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005567 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5568 entries[log_position].type);
5569 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515570 }
5571
5572 // The URLRequest::Delegate then gets informed about the redirect.
5573 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005574 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5575 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515576
5577 // The NetworkDelegate logged information in the same three events as before.
5578 for (size_t i = 0; i < 3; ++i) {
5579 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005580 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5581 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515582
5583 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5584 log_position + 1);
5585
5586 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005587 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5588 entries[log_position].type);
5589 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515590 }
5591
mikecirone8b85c432016-09-08 19:11:005592 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5593 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515594}
5595
5596// Tests handling of delegate info from a network delegate in the case of HTTP
5597// AUTH.
5598TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555599 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515600
5601 TestDelegate request_delegate;
5602 AsyncLoggingNetworkDelegate network_delegate;
5603 TestURLRequestContext context(true);
5604 context.set_network_delegate(&network_delegate);
5605 context.set_net_log(&net_log_);
5606 context.Init();
5607
5608 {
rhalavatib7bd7c792017-04-27 05:25:165609 std::unique_ptr<URLRequest> r(context.CreateRequest(
5610 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
5611 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195612 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515613 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085614 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515615
[email protected]f7022f32014-08-21 16:32:195616 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515617 base::RunLoop().Run();
5618
[email protected]f7022f32014-08-21 16:32:195619 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505620 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515621 EXPECT_EQ(1, network_delegate.created_requests());
5622 EXPECT_EQ(0, network_delegate.destroyed_requests());
5623 }
5624 EXPECT_EQ(1, network_delegate.destroyed_requests());
5625
5626 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465627 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515628 net_log_.GetEntries(&entries);
5629 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005630 // OnBeforeStartTransaction, OnHeadersReceived, OnAuthRequired, and then again
5631 // in
5632 // OnBeforeURLRequest and OnBeforeStartTransaction.
[email protected]abe1c4a2013-10-25 19:28:515633 for (size_t i = 0; i < 6; ++i) {
5634 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005635 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5636 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515637
5638 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5639 log_position + 1);
5640
5641 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005642 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5643 entries[log_position].type);
5644 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515645 }
5646
mikecirone8b85c432016-09-08 19:11:005647 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5648 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515649}
5650
tommycli59a63432015-11-06 00:10:555651// TODO(svaldez): Update tests to use EmbeddedTestServer.
5652#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515653// Tests handling of delegate info from a URLRequest::Delegate.
5654TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555655 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555656 base::FilePath(kTestFilePath));
5657
5658 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515659
5660 AsyncLoggingUrlRequestDelegate request_delegate(
5661 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5662 TestURLRequestContext context(true);
5663 context.set_network_delegate(NULL);
5664 context.set_net_log(&net_log_);
5665 context.Init();
5666
5667 {
5668 // A chunked response with delays between chunks is used to make sure that
5669 // attempts by the URLRequest delegate to log information while reading the
5670 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485671 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515672 // that it occurs.
danakj8522a25b2016-04-16 00:17:365673 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555674 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:165675 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195676 LoadStateWithParam load_state = r->GetLoadState();
5677 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515678 base::RunLoop().Run();
5679
[email protected]f7022f32014-08-21 16:32:195680 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505681 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515682 }
5683
mmenke43758e62015-05-04 21:09:465684 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515685 net_log_.GetEntries(&entries);
5686
[email protected]1826a402014-01-08 15:40:485687 size_t log_position = 0;
5688
[email protected]abe1c4a2013-10-25 19:28:515689 // The delegate info should only have been logged on header complete. Other
5690 // times it should silently be ignored.
mikecirone8b85c432016-09-08 19:11:005691 log_position = ExpectLogContainsSomewhereAfter(
5692 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5693 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515694
5695 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5696 log_position + 1);
5697
5698 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005699 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE, entries[log_position].type);
5700 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515701
mikecirone8b85c432016-09-08 19:11:005702 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5703 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515704 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005705 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515706}
tommycli59a63432015-11-06 00:10:555707#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515708
5709// Tests handling of delegate info from a URLRequest::Delegate in the case of
5710// an HTTP redirect.
5711TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555712 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515713
5714 AsyncLoggingUrlRequestDelegate request_delegate(
5715 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5716 TestURLRequestContext context(true);
5717 context.set_network_delegate(NULL);
5718 context.set_net_log(&net_log_);
5719 context.Init();
5720
5721 {
danakj8522a25b2016-04-16 00:17:365722 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555723 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165724 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195725 LoadStateWithParam load_state = r->GetLoadState();
5726 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515727 base::RunLoop().Run();
5728
[email protected]f7022f32014-08-21 16:32:195729 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505730 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515731 }
5732
mmenke43758e62015-05-04 21:09:465733 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515734 net_log_.GetEntries(&entries);
5735
5736 // Delegate info should only have been logged in OnReceivedRedirect and
5737 // OnResponseStarted.
5738 size_t log_position = 0;
5739 for (int i = 0; i < 2; ++i) {
5740 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005741 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5742 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515743
5744 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5745 log_position + 1);
5746
5747 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005748 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5749 entries[log_position].type);
5750 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515751 }
5752
mikecirone8b85c432016-09-08 19:11:005753 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5754 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515755 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005756 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515757}
5758
5759// Tests handling of delegate info from a URLRequest::Delegate in the case of
5760// an HTTP redirect, with cancellation at various points.
5761TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555762 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515763
5764 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5765 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5766 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5767 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5768 };
5769
5770 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5771 ++test_case) {
5772 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
vishal.b62985ca92015-04-17 08:45:515773 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:045774 TestURLRequestContext context(true);
[email protected]abe1c4a2013-10-25 19:28:515775 context.set_network_delegate(NULL);
5776 context.set_net_log(&net_log);
5777 context.Init();
5778
5779 {
danakj8522a25b2016-04-16 00:17:365780 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555781 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165782 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195783 LoadStateWithParam load_state = r->GetLoadState();
5784 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515785 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:505786 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515787 }
5788
mmenke43758e62015-05-04 21:09:465789 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515790 net_log.GetEntries(&entries);
5791
5792 // Delegate info is always logged in both OnReceivedRedirect and
5793 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5794 // OnResponseStarted delegate call is after cancellation, but logging is
5795 // still currently supported in that call.
5796 size_t log_position = 0;
5797 for (int i = 0; i < 2; ++i) {
5798 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005799 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5800 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515801
5802 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5803 log_position + 1);
5804
5805 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005806 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5807 entries[log_position].type);
5808 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515809 }
5810
mikecirone8b85c432016-09-08 19:11:005811 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5812 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515813 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005814 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515815 }
5816}
5817
[email protected]847c0fa92012-11-06 16:37:425818namespace {
5819
5820const char kExtraHeader[] = "Allow-Snafu";
5821const char kExtraValue[] = "fubar";
5822
5823class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205824 void OnReceivedRedirect(URLRequest* request,
5825 const RedirectInfo& redirect_info,
5826 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595827 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425828 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5829 }
5830};
5831
5832} // namespace
5833
5834TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555835 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425836
tommycli59a63432015-11-06 00:10:555837 GURL destination_url =
5838 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5839 GURL original_url =
5840 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425841 RedirectWithAdditionalHeadersDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165842 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5843 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195844 req->Start();
[email protected]255620da2013-08-19 13:14:295845 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425846
5847 std::string value;
[email protected]f7022f32014-08-21 16:32:195848 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425849 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5850 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195851 EXPECT_FALSE(req->is_pending());
5852 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425853 EXPECT_EQ(kExtraValue, d.data_received());
5854}
5855
[email protected]251a1b92012-11-13 11:01:095856namespace {
5857
5858const char kExtraHeaderToRemove[] = "To-Be-Removed";
5859
5860class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205861 void OnReceivedRedirect(URLRequest* request,
5862 const RedirectInfo& redirect_info,
5863 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595864 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095865 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5866 }
5867};
5868
5869} // namespace
5870
5871TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555872 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095873
tommycli59a63432015-11-06 00:10:555874 GURL destination_url = http_test_server()->GetURL(
5875 "/echoheader?" + std::string(kExtraHeaderToRemove));
5876 GURL original_url =
5877 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095878 RedirectWithHeaderRemovalDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165879 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5880 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195881 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5882 req->Start();
[email protected]255620da2013-08-19 13:14:295883 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095884
5885 std::string value;
[email protected]f7022f32014-08-21 16:32:195886 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095887 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195888 EXPECT_FALSE(req->is_pending());
5889 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095890 EXPECT_EQ("None", d.data_received());
5891}
5892
mmenke94f1bd92016-12-07 21:13:055893TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:445894 TestDelegate d;
5895 {
danakj8522a25b2016-04-16 00:17:365896 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165897 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
5898 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:445899
[email protected]f7022f32014-08-21 16:32:195900 r->Start();
5901 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445902
[email protected]f7022f32014-08-21 16:32:195903 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445904
[email protected]255620da2013-08-19 13:14:295905 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445906
5907 // We expect to receive OnResponseStarted even though the request has been
5908 // cancelled.
5909 EXPECT_EQ(1, d.response_started_count());
5910 EXPECT_EQ(0, d.bytes_received());
5911 EXPECT_FALSE(d.received_data_before_response());
5912 }
5913}
5914
mmenke94f1bd92016-12-07 21:13:055915TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:555916 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445917
5918 TestDelegate d;
5919 {
danakj8522a25b2016-04-16 00:17:365920 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165921 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
5922 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:445923
5924 d.set_cancel_in_response_started(true);
5925
[email protected]f7022f32014-08-21 16:32:195926 r->Start();
5927 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445928
[email protected]255620da2013-08-19 13:14:295929 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445930
5931 EXPECT_EQ(1, d.response_started_count());
5932 EXPECT_EQ(0, d.bytes_received());
5933 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:505934 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445935 }
5936}
5937
mmenke94f1bd92016-12-07 21:13:055938TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:555939 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445940
5941 TestDelegate d;
5942 {
danakj8522a25b2016-04-16 00:17:365943 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165944 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5945 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:055946
5947 d.set_cancel_in_received_data(true);
5948
5949 r->Start();
5950 EXPECT_TRUE(r->is_pending());
5951
5952 base::RunLoop().Run();
5953
5954 EXPECT_EQ(1, d.response_started_count());
5955 EXPECT_NE(0, d.received_bytes_count());
5956 EXPECT_FALSE(d.received_data_before_response());
5957 EXPECT_EQ(ERR_ABORTED, d.request_status());
5958 }
5959}
5960
5961TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
5962 ASSERT_TRUE(http_test_server()->Start());
5963
5964 TestDelegate d;
5965 {
5966 // This returns an empty response (With headers).
5967 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165968 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
5969 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:445970
5971 d.set_cancel_in_received_data(true);
5972
[email protected]f7022f32014-08-21 16:32:195973 r->Start();
5974 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445975
[email protected]255620da2013-08-19 13:14:295976 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445977
5978 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:055979 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:445980 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:505981 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445982 }
5983}
5984
mmenke94f1bd92016-12-07 21:13:055985TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:555986 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445987
5988 TestDelegate d;
5989 {
danakj8522a25b2016-04-16 00:17:365990 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165991 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
5992 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:445993
[email protected]f7022f32014-08-21 16:32:195994 r->Start();
5995 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445996
5997 // The request will be implicitly canceled when it is destroyed. The
5998 // test delegate must not post a quit message when this happens because
5999 // this test doesn't actually have a message loop. The quit message would
6000 // get put on this thread's message queue and the next test would exit
6001 // early, causing problems.
6002 d.set_quit_on_complete(false);
6003 }
6004 // expect things to just cleanup properly.
6005
kimwjdalsl2bb4ff02015-12-16 22:06:026006 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446007 // message loop
6008 EXPECT_FALSE(d.received_data_before_response());
6009 EXPECT_EQ(0, d.bytes_received());
6010}
6011
mmenke94f1bd92016-12-07 21:13:056012TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556013 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446014
6015 // populate cache
6016 {
6017 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366018 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166019 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6020 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196021 r->Start();
[email protected]255620da2013-08-19 13:14:296022 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:506023 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446024 }
6025
6026 // cancel read from cache (see bug 990242)
6027 {
6028 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366029 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166030 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6031 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196032 r->Start();
6033 r->Cancel();
[email protected]255620da2013-08-19 13:14:296034 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446035
maksim.sisovb53724b52016-09-16 05:30:506036 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446037 EXPECT_EQ(1, d.response_started_count());
6038 EXPECT_EQ(0, d.bytes_received());
6039 EXPECT_FALSE(d.received_data_before_response());
6040 }
6041}
6042
6043TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556044 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446045 HTTPUploadDataOperationTest("POST");
6046}
6047
6048TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556049 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446050 HTTPUploadDataOperationTest("PUT");
6051}
6052
6053TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556054 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446055
6056 TestDelegate d;
6057 {
danakj8522a25b2016-04-16 00:17:366058 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166059 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6060 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196061 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446062
[email protected]f7022f32014-08-21 16:32:196063 r->Start();
6064 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446065
[email protected]255620da2013-08-19 13:14:296066 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446067
maksim.sisovb53724b52016-09-16 05:30:506068 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6069 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446070
6071 EXPECT_FALSE(d.received_data_before_response());
6072 EXPECT_TRUE(d.data_received().empty());
6073 }
6074}
6075
6076TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556077 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446078
6079 TestDelegate d;
6080 {
danakj8522a25b2016-04-16 00:17:366081 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166082 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6083 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196084 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446085
[email protected]6cdfd7f2013-02-08 20:40:156086 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:446087 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026088 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446089
danakj8522a25b2016-04-16 00:17:366090 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446091
[email protected]6cdfd7f2013-02-08 20:40:156092 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446093 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476094 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446095 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196096 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146097 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076098 std::numeric_limits<uint64_t>::max(), base::Time()));
danakj8522a25b2016-04-16 00:17:366099 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:226100 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:446101
[email protected]f7022f32014-08-21 16:32:196102 r->Start();
6103 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446104
[email protected]255620da2013-08-19 13:14:296105 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446106
avibf0746c2015-12-09 19:53:146107 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296108 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6109 ASSERT_LE(size64, std::numeric_limits<int>::max());
6110 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366111 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446112
[email protected]7600d0b2013-12-08 21:43:306113 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446114
maksim.sisovb53724b52016-09-16 05:30:506115 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6116 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446117
6118 EXPECT_FALSE(d.received_data_before_response());
6119
[email protected]329b68b2012-11-14 17:54:276120 EXPECT_EQ(size, d.bytes_received());
6121 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446122 }
6123}
6124
[email protected]999dd8c2013-11-12 06:45:546125TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556126 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546127
6128 TestDelegate d;
6129 {
danakj8522a25b2016-04-16 00:17:366130 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166131 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6132 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196133 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546134
danakj8522a25b2016-04-16 00:17:366135 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546136
Jeremy Roman0579ed62017-08-29 15:56:196137 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456138 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546139 base::FilePath(FILE_PATH_LITERAL(
6140 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076141 0, std::numeric_limits<uint64_t>::max(), base::Time()));
danakj8522a25b2016-04-16 00:17:366142 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:226143 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:546144
[email protected]f7022f32014-08-21 16:32:196145 r->Start();
6146 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546147
6148 base::RunLoop().Run();
6149
[email protected]999dd8c2013-11-12 06:45:546150 EXPECT_TRUE(d.request_failed());
6151 EXPECT_FALSE(d.received_data_before_response());
6152 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506153 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546154 }
6155}
6156
mmenke56b0cbb912016-03-28 21:34:536157namespace {
6158
6159// Adds a standard set of data to an upload for chunked upload integration
6160// tests.
6161void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6162 writer->AppendData("a", 1, false);
6163 writer->AppendData("bcd", 3, false);
6164 writer->AppendData("this is a longer chunk than before.", 35, false);
6165 writer->AppendData("\r\n\r\n", 4, false);
6166 writer->AppendData("0", 1, false);
6167 writer->AppendData("2323", 4, true);
6168}
6169
6170// Checks that the upload data added in AddChunksToUpload() was echoed back from
6171// the server.
6172void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6173 // This should match the chunks sent by AddChunksToUpload().
6174 const std::string expected_data =
6175 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6176
maksim.sisovb53724b52016-09-16 05:30:506177 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6178 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536179
6180 EXPECT_FALSE(d->received_data_before_response());
6181
6182 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6183 EXPECT_EQ(expected_data, d->data_received());
6184}
6185
6186} // namespace
6187
[email protected]316c1e5e2012-09-12 15:17:446188TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556189 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446190
6191 TestDelegate d;
6192 {
danakj8522a25b2016-04-16 00:17:366193 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166194 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6195 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366196 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536197 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366198 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536199 upload_data_stream->CreateWriter();
6200 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196201 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536202 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196203 r->Start();
6204 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446205
[email protected]255620da2013-08-19 13:14:296206 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446207
[email protected]f7022f32014-08-21 16:32:196208 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446209 }
6210}
6211
[email protected]329b68b2012-11-14 17:54:276212TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556213 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276214
6215 TestDelegate d;
6216 {
danakj8522a25b2016-04-16 00:17:366217 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166218 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6219 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366220 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536221 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366222 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536223 upload_data_stream->CreateWriter();
danakj8522a25b2016-04-16 00:17:366224 r->set_upload(base::WrapUnique(upload_data_stream.release()));
[email protected]f7022f32014-08-21 16:32:196225 r->set_method("POST");
6226 r->Start();
6227 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536228 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:296229 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:276230
[email protected]f7022f32014-08-21 16:32:196231 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276232 }
6233}
6234
[email protected]316c1e5e2012-09-12 15:17:446235TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556236 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446237
6238 TestDelegate d;
6239 {
danakj8522a25b2016-04-16 00:17:366240 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166241 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6242 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366243 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536244 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366245 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536246 upload_data_stream->CreateWriter();
6247 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196248 r->set_method("POST");
6249 r->Start();
6250 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446251
[email protected]255620da2013-08-19 13:14:296252 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:536253 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:296254 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446255
[email protected]f7022f32014-08-21 16:32:196256 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446257 }
6258}
6259
6260TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556261 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446262
6263 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366264 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166265 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6266 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196267 req->Start();
[email protected]255620da2013-08-19 13:14:296268 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446269
[email protected]f7022f32014-08-21 16:32:196270 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446271
6272 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196273 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446274
6275 std::string header;
6276 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6277 EXPECT_EQ("private", header);
6278
6279 header.clear();
6280 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6281 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6282
6283 // The response has two "X-Multiple-Entries" headers.
6284 // This verfies our output has them concatenated together.
6285 header.clear();
6286 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6287 EXPECT_EQ("a, b", header);
6288}
6289
tommycli59a63432015-11-06 00:10:556290// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6291// security state. (see http://crbug.com/550977).
6292#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466293TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556294 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6295 https_test_server.SetSSLConfig(
6296 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6297 https_test_server.ServeFilesFromSourceDirectory(
6298 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466299 ASSERT_TRUE(https_test_server.Start());
6300
tommycli59a63432015-11-06 00:10:556301 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466302 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366303 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166304 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6305 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196306 request->Start();
[email protected]255620da2013-08-19 13:14:296307 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466308
6309 TransportSecurityState* security_state =
6310 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406311 TransportSecurityState::STSState sts_state;
6312 TransportSecurityState::PKPState pkp_state;
6313 EXPECT_TRUE(
6314 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6315 EXPECT_FALSE(
6316 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6317 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6318 sts_state.upgrade_mode);
6319 EXPECT_TRUE(sts_state.include_subdomains);
6320 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036321#if defined(OS_ANDROID)
6322 // Android's CertVerifyProc does not (yet) handle pins.
6323#else
martijnc0d6b622015-06-30 19:14:406324 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036325#endif
[email protected]37fd55fb2013-06-29 13:13:276326}
6327
estarka5da76702015-04-09 04:00:166328TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556329 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6330 https_test_server.ServeFilesFromSourceDirectory(
6331 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166332 ASSERT_TRUE(https_test_server.Start());
6333 // Make sure this test fails if the test server is changed to not
6334 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556335 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6336 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166337
6338 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366339 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166340 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6341 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166342 request->Start();
6343 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:166344 TransportSecurityState* security_state =
6345 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406346 TransportSecurityState::STSState sts_state;
6347 EXPECT_FALSE(
6348 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166349}
6350
estark06e0dac2015-08-07 21:56:016351namespace {
estark1614475f2016-03-10 03:46:476352const char kExpectCTStaticHostname[] = "preloaded-expect-ct.badssl.com";
dadriand476e652016-07-26 21:33:246353const char kExpectStapleStaticHostname[] = "preloaded-expect-staple.badssl.com";
6354const char kExpectStapleReportURI[] = "https://report.badssl.com/expect-staple";
estark06e0dac2015-08-07 21:56:016355const char kHPKPReportUri[] = "https://hpkp-report.test";
6356} // namespace
6357
[email protected]37fd55fb2013-06-29 13:13:276358// Tests that enabling HPKP on a domain does not affect the HSTS
6359// validity/expiration.
dadrian2faf2062016-07-16 00:03:176360TEST_F(URLRequestTestHTTP, ProcessPKP) {
estark06e0dac2015-08-07 21:56:016361 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556362 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6363 https_test_server.SetSSLConfig(
6364 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6365 https_test_server.ServeFilesFromSourceDirectory(
6366 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276367 ASSERT_TRUE(https_test_server.Start());
6368
tommycli59a63432015-11-06 00:10:556369 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166370
[email protected]37fd55fb2013-06-29 13:13:276371 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366372 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166373 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6374 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196375 request->Start();
[email protected]255620da2013-08-19 13:14:296376 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276377 TransportSecurityState* security_state =
6378 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406379 TransportSecurityState::STSState sts_state;
6380 TransportSecurityState::PKPState pkp_state;
6381 EXPECT_FALSE(
6382 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6383 EXPECT_TRUE(
6384 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6385 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
6386 sts_state.upgrade_mode);
6387 EXPECT_FALSE(sts_state.include_subdomains);
6388 EXPECT_FALSE(pkp_state.include_subdomains);
6389 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:016390 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:406391 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:466392}
6393
estark06e0dac2015-08-07 21:56:016394// Tests that reports get sent on HPKP violations when a report-uri is set.
dadrian2faf2062016-07-16 00:03:176395TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:016396 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556397 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6398 https_test_server.SetSSLConfig(
6399 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6400 https_test_server.ServeFilesFromSourceDirectory(
6401 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016402 ASSERT_TRUE(https_test_server.Start());
6403
tommycli59a63432015-11-06 00:10:556404 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016405
6406 // Set up a pin for |test_server_hostname|.
6407 TransportSecurityState security_state;
6408 const base::Time current_time(base::Time::Now());
6409 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
6410 HashValueVector hashes;
6411 HashValue hash1;
6412 HashValue hash2;
6413 // The values here don't matter, as long as they are different from
6414 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:446415 ASSERT_TRUE(
6416 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6417 ASSERT_TRUE(
6418 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016419 hashes.push_back(hash1);
6420 hashes.push_back(hash2);
6421 security_state.AddHPKP(test_server_hostname, expiry,
6422 false, /* include subdomains */
6423 hashes, report_uri);
6424
6425 MockCertificateReportSender mock_report_sender;
6426 security_state.SetReportSender(&mock_report_sender);
6427
6428 // Set up a MockCertVerifier to trigger a violation of the previously
6429 // set pin.
6430 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6431 ASSERT_TRUE(cert);
6432
6433 MockCertVerifier cert_verifier;
6434 CertVerifyResult verify_result;
6435 verify_result.verified_cert = cert;
6436 verify_result.is_issued_by_known_root = true;
6437 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446438 ASSERT_TRUE(
6439 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016440 verify_result.public_key_hashes.push_back(hash3);
6441 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6442
6443 TestNetworkDelegate network_delegate;
6444 TestURLRequestContext context(true);
6445 context.set_transport_security_state(&security_state);
6446 context.set_network_delegate(&network_delegate);
6447 context.set_cert_verifier(&cert_verifier);
6448 context.Init();
6449
6450 // Now send a request to trigger the violation.
6451 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366452 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166453 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
6454 TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016455 violating_request->Start();
6456 base::RunLoop().Run();
6457
6458 // Check that a report was sent.
6459 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6460 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446461 EXPECT_EQ("application/json; charset=utf-8",
6462 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366463 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016464 base::JSONReader::Read(mock_report_sender.latest_report()));
6465 ASSERT_TRUE(value);
jdoerriedc72ee942016-12-07 15:43:286466 ASSERT_TRUE(value->IsType(base::Value::Type::DICTIONARY));
estark06e0dac2015-08-07 21:56:016467 base::DictionaryValue* report_dict;
6468 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6469 std::string report_hostname;
6470 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6471 EXPECT_EQ(test_server_hostname, report_hostname);
6472}
6473
6474// Tests that reports get sent on requests with
6475// Public-Key-Pins-Report-Only headers.
dadrian2faf2062016-07-16 00:03:176476TEST_F(URLRequestTestHTTP, ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016477 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556478 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6479 https_test_server.SetSSLConfig(
6480 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6481 https_test_server.ServeFilesFromSourceDirectory(
6482 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016483 ASSERT_TRUE(https_test_server.Start());
6484
tommycli59a63432015-11-06 00:10:556485 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016486
6487 TransportSecurityState security_state;
6488 MockCertificateReportSender mock_report_sender;
6489 security_state.SetReportSender(&mock_report_sender);
6490
6491 // Set up a MockCertVerifier to violate the pin in the Report-Only
6492 // header.
6493 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6494 ASSERT_TRUE(cert);
6495
6496 MockCertVerifier cert_verifier;
6497 CertVerifyResult verify_result;
6498 verify_result.verified_cert = cert;
6499 verify_result.is_issued_by_known_root = true;
6500 HashValue hash;
6501 // This value doesn't matter, as long as it is different from the pins
6502 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446503 ASSERT_TRUE(
6504 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016505 verify_result.public_key_hashes.push_back(hash);
6506 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6507
6508 TestNetworkDelegate network_delegate;
6509 TestURLRequestContext context(true);
6510 context.set_transport_security_state(&security_state);
6511 context.set_network_delegate(&network_delegate);
6512 context.set_cert_verifier(&cert_verifier);
6513 context.Init();
6514
6515 // Now send a request to trigger the violation.
6516 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366517 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556518 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:166519 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016520 violating_request->Start();
6521 base::RunLoop().Run();
6522
6523 // Check that a report was sent.
6524 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6525 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446526 EXPECT_EQ("application/json; charset=utf-8",
6527 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366528 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016529 base::JSONReader::Read(mock_report_sender.latest_report()));
6530 ASSERT_TRUE(value);
jdoerriedc72ee942016-12-07 15:43:286531 ASSERT_TRUE(value->IsType(base::Value::Type::DICTIONARY));
estark06e0dac2015-08-07 21:56:016532 base::DictionaryValue* report_dict;
6533 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6534 std::string report_hostname;
6535 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6536 EXPECT_EQ(test_server_hostname, report_hostname);
6537}
6538
6539// Tests that reports do not get sent on requests with
6540// Public-Key-Pins-Report-Only headers that don't have pin violations.
dadrian2faf2062016-07-16 00:03:176541TEST_F(URLRequestTestHTTP, ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016542 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556543 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6544 https_test_server.SetSSLConfig(
6545 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6546 https_test_server.ServeFilesFromSourceDirectory(
6547 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016548 ASSERT_TRUE(https_test_server.Start());
6549
tommycli59a63432015-11-06 00:10:556550 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016551
6552 TransportSecurityState security_state;
6553 MockCertificateReportSender mock_report_sender;
6554 security_state.SetReportSender(&mock_report_sender);
6555
6556 TestNetworkDelegate network_delegate;
6557 MockCertVerifier mock_cert_verifier;
6558 TestURLRequestContext context(true);
6559 context.set_transport_security_state(&security_state);
6560 context.set_network_delegate(&network_delegate);
6561 context.set_cert_verifier(&mock_cert_verifier);
6562 mock_cert_verifier.set_default_result(OK);
6563 context.Init();
6564
6565 // Now send a request that does not trigger the violation.
6566 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366567 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556568 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:166569 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016570 request->Start();
6571 base::RunLoop().Run();
6572
6573 // Check that a report was not sent.
6574 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6575 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6576}
6577
estarka5da76702015-04-09 04:00:166578TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556579 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6580 https_test_server.ServeFilesFromSourceDirectory(
6581 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166582 ASSERT_TRUE(https_test_server.Start());
6583 // Make sure this test fails if the test server is changed to not
6584 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556585 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6586 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166587
6588 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366589 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166590 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6591 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166592 request->Start();
6593 base::RunLoop().Run();
6594
6595 TransportSecurityState* security_state =
6596 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406597 TransportSecurityState::PKPState pkp_state;
6598 EXPECT_FALSE(
6599 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166600}
6601
dadriandf302c42016-06-10 18:48:596602TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6603 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6604 https_test_server.SetSSLConfig(
6605 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6606 https_test_server.ServeFilesFromSourceDirectory(
6607 base::FilePath(kTestFilePath));
6608 ASSERT_TRUE(https_test_server.Start());
6609
6610 // Set up a MockCertVerifier to be a local root that violates the pin
6611 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6612 ASSERT_TRUE(cert);
6613
6614 MockCertVerifier cert_verifier;
6615 CertVerifyResult verify_result;
6616 verify_result.verified_cert = cert;
6617 verify_result.is_issued_by_known_root = false;
6618 HashValue hash;
6619 ASSERT_TRUE(
6620 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6621 verify_result.public_key_hashes.push_back(hash);
6622 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6623 cert_verifier.set_default_result(OK);
6624
6625 std::string test_server_hostname = https_test_server.GetURL("/").host();
6626
6627 // Set up HPKP
6628 base::Time current_time = base::Time::Now();
6629 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
6630 HashValue pin;
6631 ASSERT_TRUE(
6632 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
6633 HashValueVector hashes;
6634 hashes.push_back(pin);
6635 GURL report_uri(kHPKPReportUri);
6636 TransportSecurityState security_state;
6637 security_state.AddHPKP(test_server_hostname, expiry,
6638 false, /* include subdomains */
6639 hashes, report_uri);
6640
6641 TestNetworkDelegate network_delegate;
6642 TestURLRequestContext context(true);
6643 context.set_transport_security_state(&security_state);
6644 context.set_network_delegate(&network_delegate);
6645 context.set_cert_verifier(&cert_verifier);
6646 context.Init();
6647
6648 TestDelegate d;
6649 std::unique_ptr<URLRequest> request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166650 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6651 TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:596652 request->Start();
6653 base::RunLoop().Run();
6654
6655 TransportSecurityState::PKPState pkp_state;
6656 EXPECT_TRUE(
6657 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
6658 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6659}
6660
[email protected]242d8562012-10-30 21:20:466661TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556662 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6663 https_test_server.SetSSLConfig(
6664 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6665 https_test_server.ServeFilesFromSourceDirectory(
6666 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466667 ASSERT_TRUE(https_test_server.Start());
6668
tommycli59a63432015-11-06 00:10:556669 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166670
[email protected]242d8562012-10-30 21:20:466671 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366672 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556673 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166674 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196675 request->Start();
[email protected]255620da2013-08-19 13:14:296676 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466677
6678 // We should have set parameters from the first header, not the second.
6679 TransportSecurityState* security_state =
6680 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406681 TransportSecurityState::STSState sts_state;
6682 EXPECT_TRUE(
6683 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6684 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6685 sts_state.upgrade_mode);
6686 EXPECT_FALSE(sts_state.include_subdomains);
6687 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466688}
6689
[email protected]9f972ec2013-04-10 20:24:366690TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556691 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6692 https_test_server.SetSSLConfig(
6693 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6694 https_test_server.ServeFilesFromSourceDirectory(
6695 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366696 ASSERT_TRUE(https_test_server.Start());
6697
tommycli59a63432015-11-06 00:10:556698 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166699
[email protected]9f972ec2013-04-10 20:24:366700 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366701 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556702 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166703 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196704 request->Start();
[email protected]255620da2013-08-19 13:14:296705 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366706
6707 // We should have set parameters from the first header, not the second.
6708 TransportSecurityState* security_state =
6709 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406710 TransportSecurityState::STSState sts_state;
6711 TransportSecurityState::PKPState pkp_state;
6712 EXPECT_TRUE(
6713 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6714 EXPECT_TRUE(
6715 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6716 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6717 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036718#if defined(OS_ANDROID)
6719 // Android's CertVerifyProc does not (yet) handle pins.
6720#else
martijnc0d6b622015-06-30 19:14:406721 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036722#endif
martijnc0d6b622015-06-30 19:14:406723 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366724
[email protected]a165f092013-06-12 16:10:056725 // Even though there is an HSTS header asserting includeSubdomains, it is
6726 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406727 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056728 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406729 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366730}
6731
[email protected]37fd55fb2013-06-29 13:13:276732// Tests that when multiple HPKP headers are present, asserting different
6733// policies, that only the first such policy is processed.
6734TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556735 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6736 https_test_server.SetSSLConfig(
6737 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6738 https_test_server.ServeFilesFromSourceDirectory(
6739 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276740 ASSERT_TRUE(https_test_server.Start());
6741
tommycli59a63432015-11-06 00:10:556742 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166743
[email protected]37fd55fb2013-06-29 13:13:276744 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366745 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556746 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
rhalavatib7bd7c792017-04-27 05:25:166747 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196748 request->Start();
[email protected]255620da2013-08-19 13:14:296749 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276750
6751 TransportSecurityState* security_state =
6752 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406753 TransportSecurityState::STSState sts_state;
6754 TransportSecurityState::PKPState pkp_state;
6755 EXPECT_TRUE(
6756 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6757 EXPECT_TRUE(
6758 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6759 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6760 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036761#if defined(OS_ANDROID)
6762 // Android's CertVerifyProc does not (yet) handle pins.
6763#else
martijnc0d6b622015-06-30 19:14:406764 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036765#endif
martijnc0d6b622015-06-30 19:14:406766 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276767
martijnc0d6b622015-06-30 19:14:406768 EXPECT_TRUE(sts_state.include_subdomains);
6769 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276770}
6771
estark1614475f2016-03-10 03:46:476772// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6773// called.
6774class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6775 public:
6776 MockExpectCTReporter() : num_failures_(0) {}
6777 ~MockExpectCTReporter() override {}
6778
6779 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6780 const GURL& report_uri,
estarkae028b462017-06-20 23:25:016781 base::Time expiration,
estarkbf1b52962017-05-05 17:05:256782 const X509Certificate* validated_certificate_chain,
6783 const X509Certificate* served_certificate_chain,
6784 const SignedCertificateTimestampAndStatusList&
6785 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:476786 num_failures_++;
6787 }
6788
6789 uint32_t num_failures() { return num_failures_; }
6790
6791 private:
6792 uint32_t num_failures_;
6793};
6794
estark1614475f2016-03-10 03:46:476795// A CTPolicyEnforcer that returns a default CertPolicyCompliance value
6796// for every certificate.
6797class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6798 public:
6799 MockCTPolicyEnforcer()
6800 : default_result_(
6801 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) {}
6802 ~MockCTPolicyEnforcer() override {}
6803
6804 ct::CertPolicyCompliance DoesConformToCertPolicy(
6805 X509Certificate* cert,
6806 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:206807 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:476808 return default_result_;
6809 }
6810
6811 void set_default_result(ct::CertPolicyCompliance default_result) {
6812 default_result_ = default_result;
6813 }
6814
6815 private:
6816 ct::CertPolicyCompliance default_result_;
6817};
6818
Emily Stark4cfecf072017-08-08 01:05:516819// Tests that Expect CT headers for the preload list are processed correctly.
6820TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
xunjieli815ad5b2017-07-18 15:51:356821#if !BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
6822 SetTransportSecurityStateSourceForTesting(&test0::kHSTSSource);
6823#endif
estark1614475f2016-03-10 03:46:476824 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6825 https_test_server.SetSSLConfig(
6826 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6827 https_test_server.ServeFilesFromSourceDirectory(
6828 base::FilePath(kTestFilePath));
6829 ASSERT_TRUE(https_test_server.Start());
6830
6831 MockExpectCTReporter reporter;
6832 TransportSecurityState transport_security_state;
6833 transport_security_state.enable_static_expect_ct_ = true;
6834 transport_security_state.SetExpectCTReporter(&reporter);
6835
6836 // Set up a MockCertVerifier to accept the certificate that the server sends.
6837 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6838 ASSERT_TRUE(cert);
6839 MockCertVerifier cert_verifier;
6840 CertVerifyResult verify_result;
6841 verify_result.verified_cert = cert;
6842 verify_result.is_issued_by_known_root = true;
6843 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6844
rsleevi22cae1672016-12-28 01:53:366845 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
6846 // CT violation.
6847 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:476848 MockCTPolicyEnforcer ct_policy_enforcer;
6849 ct_policy_enforcer.set_default_result(
6850 ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS);
6851
6852 TestNetworkDelegate network_delegate;
6853 // Use a MockHostResolver (which by default maps all hosts to
6854 // 127.0.0.1) so that the request can be sent to a site on the Expect
6855 // CT preload list.
6856 MockHostResolver host_resolver;
6857 TestURLRequestContext context(true);
6858 context.set_host_resolver(&host_resolver);
6859 context.set_transport_security_state(&transport_security_state);
6860 context.set_network_delegate(&network_delegate);
6861 context.set_cert_verifier(&cert_verifier);
6862 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:466863 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:476864 context.Init();
6865
6866 // Now send a request to trigger the violation.
6867 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:516868 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:476869 GURL::Replacements replace_host;
6870 replace_host.SetHostStr(kExpectCTStaticHostname);
6871 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:166872 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
6873 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:476874 violating_request->Start();
6875 base::RunLoop().Run();
6876
6877 EXPECT_EQ(1u, reporter.num_failures());
6878}
Emily Stark4cfecf072017-08-08 01:05:516879
6880// Tests that Expect CT HTTP headers are processed correctly.
6881TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
6882 base::test::ScopedFeatureList feature_list;
6883 feature_list.InitAndEnableFeature(
6884 TransportSecurityState::kDynamicExpectCTFeature);
6885
6886 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6887 https_test_server.SetSSLConfig(
6888 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6889 https_test_server.ServeFilesFromSourceDirectory(
6890 base::FilePath(kTestFilePath));
6891 ASSERT_TRUE(https_test_server.Start());
6892
6893 MockExpectCTReporter reporter;
6894 TransportSecurityState transport_security_state;
6895 transport_security_state.SetExpectCTReporter(&reporter);
6896
6897 // Set up a MockCertVerifier to accept the certificate that the server sends.
6898 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6899 ASSERT_TRUE(cert);
6900 MockCertVerifier cert_verifier;
6901 CertVerifyResult verify_result;
6902 verify_result.verified_cert = cert;
6903 verify_result.is_issued_by_known_root = true;
6904 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6905
6906 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
6907 // compliance.
6908 DoNothingCTVerifier ct_verifier;
6909 MockCTPolicyEnforcer ct_policy_enforcer;
6910 ct_policy_enforcer.set_default_result(
6911 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS);
6912
6913 TestNetworkDelegate network_delegate;
6914 // Use a MockHostResolver (which by default maps all hosts to
6915 // 127.0.0.1).
6916 MockHostResolver host_resolver;
6917 TestURLRequestContext context(true);
6918 context.set_host_resolver(&host_resolver);
6919 context.set_transport_security_state(&transport_security_state);
6920 context.set_network_delegate(&network_delegate);
6921 context.set_cert_verifier(&cert_verifier);
6922 context.set_cert_transparency_verifier(&ct_verifier);
6923 context.set_ct_policy_enforcer(&ct_policy_enforcer);
6924 context.Init();
6925
6926 // Now send a request to trigger the header processing.
6927 TestDelegate d;
6928 GURL url = https_test_server.GetURL("/expect-ct-header.html");
6929 std::unique_ptr<URLRequest> request(context.CreateRequest(
6930 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
6931 request->Start();
6932 base::RunLoop().Run();
6933
6934 TransportSecurityState::ExpectCTState state;
6935 ASSERT_TRUE(
6936 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
6937 EXPECT_TRUE(state.enforce);
6938 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
6939}
6940
6941// Tests that if multiple Expect CT HTTP headers are sent, they are all
6942// processed.
6943TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
6944 base::test::ScopedFeatureList feature_list;
6945 feature_list.InitAndEnableFeature(
6946 TransportSecurityState::kDynamicExpectCTFeature);
6947
6948 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6949 https_test_server.SetSSLConfig(
6950 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6951 https_test_server.ServeFilesFromSourceDirectory(
6952 base::FilePath(kTestFilePath));
6953 ASSERT_TRUE(https_test_server.Start());
6954
6955 MockExpectCTReporter reporter;
6956 TransportSecurityState transport_security_state;
6957 transport_security_state.SetExpectCTReporter(&reporter);
6958
6959 // Set up a MockCertVerifier to accept the certificate that the server sends.
6960 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6961 ASSERT_TRUE(cert);
6962 MockCertVerifier cert_verifier;
6963 CertVerifyResult verify_result;
6964 verify_result.verified_cert = cert;
6965 verify_result.is_issued_by_known_root = true;
6966 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6967
6968 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
6969 // compliance.
6970 DoNothingCTVerifier ct_verifier;
6971 MockCTPolicyEnforcer ct_policy_enforcer;
6972 ct_policy_enforcer.set_default_result(
6973 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS);
6974
6975 TestNetworkDelegate network_delegate;
6976 // Use a MockHostResolver (which by default maps all hosts to
6977 // 127.0.0.1).
6978 MockHostResolver host_resolver;
6979 TestURLRequestContext context(true);
6980 context.set_host_resolver(&host_resolver);
6981 context.set_transport_security_state(&transport_security_state);
6982 context.set_network_delegate(&network_delegate);
6983 context.set_cert_verifier(&cert_verifier);
6984 context.set_cert_transparency_verifier(&ct_verifier);
6985 context.set_ct_policy_enforcer(&ct_policy_enforcer);
6986 context.Init();
6987
6988 // Now send a request to trigger the header processing.
6989 TestDelegate d;
6990 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
6991 std::unique_ptr<URLRequest> request(context.CreateRequest(
6992 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
6993 request->Start();
6994 base::RunLoop().Run();
6995
6996 TransportSecurityState::ExpectCTState state;
6997 ASSERT_TRUE(
6998 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
6999 EXPECT_TRUE(state.enforce);
7000 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7001}
7002
mmenkefd9d15c2017-06-29 13:45:547003#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477004
mmenkefd9d15c2017-06-29 13:45:547005#if BUILDFLAG(ENABLE_REPORTING)
juliatuttle2b8dd2d12017-04-12 21:27:417006namespace {
7007
7008class TestReportingService : public ReportingService {
7009 public:
7010 struct Header {
7011 GURL url;
7012 std::string header_value;
7013 };
7014
juliatuttle2b8dd2d12017-04-12 21:27:417015 const std::vector<Header>& headers() { return headers_; }
7016
juliatuttle1d92f0152017-04-28 17:19:217017 // ReportingService implementation:
7018
7019 ~TestReportingService() override {}
7020
juliatuttle2b8dd2d12017-04-12 21:27:417021 void QueueReport(const GURL& url,
7022 const std::string& group,
7023 const std::string& type,
7024 std::unique_ptr<const base::Value> body) override {
7025 NOTIMPLEMENTED();
7026 }
7027
7028 void ProcessHeader(const GURL& url,
7029 const std::string& header_value) override {
7030 headers_.push_back({url, header_value});
7031 }
7032
juliatuttleaeb1abc2017-05-04 21:14:387033 void RemoveBrowsingData(
7034 int data_type_mask,
7035 base::Callback<bool(const GURL&)> origin_filter) override {
7036 NOTIMPLEMENTED();
7037 }
7038
juliatuttle2b8dd2d12017-04-12 21:27:417039 private:
7040 std::vector<Header> headers_;
7041};
7042
7043std::unique_ptr<test_server::HttpResponse> SendReportToHeader(
7044 const test_server::HttpRequest& request) {
7045 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7046 new test_server::BasicHttpResponse);
7047 http_response->set_code(HTTP_OK);
7048 http_response->AddCustomHeader("Report-To", "foo");
7049 http_response->AddCustomHeader("Report-To", "bar");
7050 return std::move(http_response);
7051}
7052
7053} // namespace
7054
7055TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderNoService) {
7056 http_test_server()->RegisterRequestHandler(base::Bind(&SendReportToHeader));
7057 ASSERT_TRUE(http_test_server()->Start());
7058 GURL request_url = http_test_server()->GetURL("/");
7059
7060 TestNetworkDelegate network_delegate;
7061 TestURLRequestContext context(true);
7062 context.set_network_delegate(&network_delegate);
7063 context.Init();
7064
7065 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167066 std::unique_ptr<URLRequest> request(context.CreateRequest(
7067 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417068 request->Start();
7069 base::RunLoop().Run();
7070}
7071
7072TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderHTTP) {
7073 http_test_server()->RegisterRequestHandler(base::Bind(&SendReportToHeader));
7074 ASSERT_TRUE(http_test_server()->Start());
7075 GURL request_url = http_test_server()->GetURL("/");
7076
7077 TestNetworkDelegate network_delegate;
7078 TestReportingService reporting_service;
7079 TestURLRequestContext context(true);
7080 context.set_network_delegate(&network_delegate);
7081 context.set_reporting_service(&reporting_service);
7082 context.Init();
7083
7084 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167085 std::unique_ptr<URLRequest> request(context.CreateRequest(
7086 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417087 request->Start();
7088 base::RunLoop().Run();
7089
7090 EXPECT_TRUE(reporting_service.headers().empty());
7091}
7092
7093TEST_F(URLRequestTestHTTP, ProcessReportToHeaderHTTPS) {
7094 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7095 https_test_server.RegisterRequestHandler(base::Bind(&SendReportToHeader));
7096 ASSERT_TRUE(https_test_server.Start());
7097 GURL request_url = https_test_server.GetURL("/");
7098
7099 TestNetworkDelegate network_delegate;
7100 TestReportingService reporting_service;
7101 TestURLRequestContext context(true);
7102 context.set_network_delegate(&network_delegate);
7103 context.set_reporting_service(&reporting_service);
7104 context.Init();
7105
7106 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167107 std::unique_ptr<URLRequest> request(context.CreateRequest(
7108 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417109 request->Start();
7110 base::RunLoop().Run();
7111
7112 ASSERT_EQ(1u, reporting_service.headers().size());
7113 EXPECT_EQ(request_url, reporting_service.headers()[0].url);
7114 EXPECT_EQ("foo, bar", reporting_service.headers()[0].header_value);
7115}
7116
Julia Tuttlef9b74062017-07-27 14:44:057117TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderInvalidHttps) {
juliatuttle2b8dd2d12017-04-12 21:27:417118 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7119 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
7120 https_test_server.RegisterRequestHandler(base::Bind(&SendReportToHeader));
7121 ASSERT_TRUE(https_test_server.Start());
7122 GURL request_url = https_test_server.GetURL("/");
7123
7124 TestNetworkDelegate network_delegate;
7125 TestReportingService reporting_service;
7126 TestURLRequestContext context(true);
7127 context.set_network_delegate(&network_delegate);
7128 context.set_reporting_service(&reporting_service);
7129 context.Init();
7130
7131 TestDelegate d;
7132 d.set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:167133 std::unique_ptr<URLRequest> request(context.CreateRequest(
7134 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417135 request->Start();
7136 base::RunLoop().Run();
7137
7138 EXPECT_TRUE(d.have_certificate_errors());
7139 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
7140 EXPECT_TRUE(reporting_service.headers().empty());
7141}
mmenkefd9d15c2017-06-29 13:45:547142#endif // BUILDFLAG(ENABLE_REPORTING)
tommycli59a63432015-11-06 00:10:557143
Julia Tuttlef9b74062017-07-27 14:44:057144namespace {
7145
7146class TestNetworkErrorLoggingDelegate : public NetworkErrorLoggingDelegate {
7147 public:
7148 struct Header {
7149 Header() {}
7150 ~Header() {}
7151
7152 url::Origin origin;
7153 std::string value;
7154 };
7155
7156 struct NetworkError {
7157 NetworkError() {}
7158 ~NetworkError() {}
7159
7160 url::Origin origin;
7161 Error error;
7162 NetworkErrorLoggingDelegate::ErrorDetails details;
7163 };
7164
7165 const std::vector<Header>& headers() { return headers_; }
7166 const std::vector<NetworkError>& errors() { return errors_; }
7167
7168 // NetworkErrorLoggingDelegate implementation:
7169
7170 ~TestNetworkErrorLoggingDelegate() override {}
7171
7172 void SetReportingService(ReportingService* reporting_service) override {
7173 NOTREACHED();
7174 }
7175
7176 void OnHeader(const url::Origin& origin, const std::string& value) override {
7177 Header header;
7178 header.origin = origin;
7179 header.value = value;
7180 headers_.push_back(header);
7181 }
7182
7183 void OnNetworkError(const url::Origin& origin,
7184 Error error,
7185 ErrorDetailsCallback details_callback) override {
7186 NetworkError network_error;
7187 network_error.origin = origin;
7188 network_error.error = error;
7189 std::move(details_callback).Run(&network_error.details);
7190 errors_.push_back(network_error);
7191 }
7192
7193 private:
7194 std::vector<Header> headers_;
7195 std::vector<NetworkError> errors_;
7196};
7197
7198std::unique_ptr<test_server::HttpResponse> SendNelHeader(
7199 const test_server::HttpRequest& request) {
7200 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7201 new test_server::BasicHttpResponse);
7202 http_response->set_code(HTTP_OK);
7203 http_response->AddCustomHeader(NetworkErrorLoggingDelegate::kHeaderName,
7204 "foo");
7205 return std::move(http_response);
7206}
7207
7208} // namespace
7209
7210TEST_F(URLRequestTestHTTP, DontProcessNelHeaderNoDelegate) {
7211 http_test_server()->RegisterRequestHandler(base::Bind(&SendNelHeader));
7212 ASSERT_TRUE(http_test_server()->Start());
7213 GURL request_url = http_test_server()->GetURL("/");
7214
7215 TestNetworkDelegate network_delegate;
7216 TestURLRequestContext context(true);
7217 context.set_network_delegate(&network_delegate);
7218 context.Init();
7219
7220 TestDelegate d;
7221 std::unique_ptr<URLRequest> request(context.CreateRequest(
7222 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7223 request->Start();
7224 base::RunLoop().Run();
7225}
7226
7227TEST_F(URLRequestTestHTTP, DontProcessNelHeaderHttp) {
7228 http_test_server()->RegisterRequestHandler(base::Bind(&SendNelHeader));
7229 ASSERT_TRUE(http_test_server()->Start());
7230 GURL request_url = http_test_server()->GetURL("/");
7231
7232 TestNetworkDelegate network_delegate;
7233 TestNetworkErrorLoggingDelegate nel_delegate;
7234 TestURLRequestContext context(true);
7235 context.set_network_delegate(&network_delegate);
7236 context.set_network_error_logging_delegate(&nel_delegate);
7237 context.Init();
7238
7239 TestDelegate d;
7240 std::unique_ptr<URLRequest> request(context.CreateRequest(
7241 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7242 request->Start();
7243 base::RunLoop().Run();
7244
7245 EXPECT_TRUE(nel_delegate.headers().empty());
7246}
7247
7248TEST_F(URLRequestTestHTTP, ProcessNelHeaderHttps) {
7249 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7250 https_test_server.RegisterRequestHandler(base::Bind(&SendNelHeader));
7251 ASSERT_TRUE(https_test_server.Start());
7252 GURL request_url = https_test_server.GetURL("/");
7253
7254 TestNetworkDelegate network_delegate;
7255 TestNetworkErrorLoggingDelegate nel_delegate;
7256 TestURLRequestContext context(true);
7257 context.set_network_delegate(&network_delegate);
7258 context.set_network_error_logging_delegate(&nel_delegate);
7259 context.Init();
7260
7261 TestDelegate d;
7262 std::unique_ptr<URLRequest> request(context.CreateRequest(
7263 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7264 request->Start();
7265 base::RunLoop().Run();
7266
7267 ASSERT_EQ(1u, nel_delegate.headers().size());
7268 EXPECT_EQ(url::Origin(request_url), nel_delegate.headers()[0].origin);
7269 EXPECT_EQ("foo", nel_delegate.headers()[0].value);
7270}
7271
7272TEST_F(URLRequestTestHTTP, DontProcessNelHeaderInvalidHttps) {
7273 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7274 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
7275 https_test_server.RegisterRequestHandler(base::Bind(&SendNelHeader));
7276 ASSERT_TRUE(https_test_server.Start());
7277 GURL request_url = https_test_server.GetURL("/");
7278
7279 TestNetworkDelegate network_delegate;
7280 TestNetworkErrorLoggingDelegate nel_delegate;
7281 TestURLRequestContext context(true);
7282 context.set_network_delegate(&network_delegate);
7283 context.set_network_error_logging_delegate(&nel_delegate);
7284 context.Init();
7285
7286 TestDelegate d;
7287 d.set_allow_certificate_errors(true);
7288 std::unique_ptr<URLRequest> request(context.CreateRequest(
7289 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7290 request->Start();
7291 base::RunLoop().Run();
7292
7293 EXPECT_TRUE(d.have_certificate_errors());
7294 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
7295 EXPECT_TRUE(nel_delegate.headers().empty());
7296}
7297
[email protected]316c1e5e2012-09-12 15:17:447298TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557299 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447300
7301 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367302 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557303 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167304 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197305 req->Start();
[email protected]255620da2013-08-19 13:14:297306 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447307
7308 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197309 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447310 EXPECT_EQ("text/html", mime_type);
7311
7312 std::string charset;
[email protected]f7022f32014-08-21 16:32:197313 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447314 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197315 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447316}
7317
[email protected]02494ec2014-05-07 15:05:297318TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347319 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347320 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347321 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027322 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347323
7324 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507325 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347326}
7327
brettwa1228ebb2016-10-28 03:51:347328#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297329TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7330 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7331 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457332 FileProtocolHandler file_protocol_handler(
7333 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297334 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7335
7336 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507337 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297338}
7339
[email protected]588614c22013-08-16 00:09:027340TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557341 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447342
7343 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367344 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557345 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167346 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197347 req->Start();
[email protected]255620da2013-08-19 13:14:297348 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447349
maksim.sisovb53724b52016-09-16 05:30:507350 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307351
7352 // The redirect should have been rejected before reporting it to the caller.
7353 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447354}
brettwa1228ebb2016-10-28 03:51:347355#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447356
[email protected]588614c22013-08-16 00:09:027357TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557358 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027359
7360 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367361 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557362 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167363 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197364 req->Start();
fdoray5eeb7642016-06-22 16:11:287365 base::RunLoop().Run();
[email protected]588614c22013-08-16 00:09:027366
maksim.sisovb53724b52016-09-16 05:30:507367 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307368
7369 // The redirect should have been rejected before reporting it to the
7370 // caller. See https://crbug.com/723796
7371 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027372}
7373
davidbend894710b2017-06-06 19:28:307374// Test that redirects to invalid URLs are rejected. See
7375// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447376TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557377 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447378
7379 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367380 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557381 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167382 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197383 req->Start();
[email protected]255620da2013-08-19 13:14:297384 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447385
davidbend894710b2017-06-06 19:28:307386 EXPECT_EQ(1, d.response_started_count());
7387 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7388
7389 // The redirect should have been rejected before reporting it to the caller.
7390 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447391}
7392
[email protected]e50efea2014-03-24 18:41:007393// Make sure redirects are cached, despite not reading their bodies.
7394TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557395 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007396 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557397 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007398
7399 {
7400 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167401 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7402 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197403 req->Start();
[email protected]e50efea2014-03-24 18:41:007404 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:507405 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007406 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557407 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007408 }
7409
7410 {
7411 TestDelegate d;
7412 d.set_quit_on_redirect(true);
rhalavatib7bd7c792017-04-27 05:25:167413 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7414 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197415 req->Start();
[email protected]e50efea2014-03-24 18:41:007416 base::RunLoop().Run();
7417
7418 EXPECT_EQ(1, d.received_redirect_count());
7419 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197420 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007421
[email protected]f7022f32014-08-21 16:32:197422 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:007423 base::RunLoop().Run();
7424 EXPECT_EQ(1, d.received_redirect_count());
7425 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507426 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557427 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007428 }
7429}
7430
7431// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7432// when the headers are read, since the body won't have been read.
7433TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557434 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007435 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557436 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007437
7438 {
7439 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557440 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007441 default_network_delegate_.set_redirect_on_headers_received_url(
7442 redirect_to_url);
7443
7444 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167445 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7446 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197447 req->Start();
[email protected]e50efea2014-03-24 18:41:007448 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:507449 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007450 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197451 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007452 }
7453
7454 {
7455 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167456 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7457 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197458 req->Start();
[email protected]e50efea2014-03-24 18:41:007459 base::RunLoop().Run();
7460
maksim.sisovb53724b52016-09-16 05:30:507461 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197462 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007463 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197464 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007465 }
7466}
7467
[email protected]5f714132014-03-26 10:41:167468// Tests that redirection to an unsafe URL is allowed when it has been marked as
7469// safe.
7470TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557471 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167472
7473 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
7474 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7475 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7476
7477 TestDelegate d;
7478 {
danakj8522a25b2016-04-16 00:17:367479 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167480 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7481 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167482
[email protected]f7022f32014-08-21 16:32:197483 r->Start();
[email protected]5f714132014-03-26 10:41:167484 base::RunLoop().Run();
7485
maksim.sisovb53724b52016-09-16 05:30:507486 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197487 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:197488 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:167489 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
7490 }
7491}
7492
7493// Tests that a redirect to a different unsafe URL is blocked, even after adding
7494// some other URL to the whitelist.
7495TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:557496 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167497
7498 GURL unsafe_url("data:text/html,something");
7499 GURL different_unsafe_url("data:text/html,something-else");
7500 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7501 default_network_delegate_.set_allowed_unsafe_redirect_url(
7502 different_unsafe_url);
7503
7504 TestDelegate d;
7505 {
danakj8522a25b2016-04-16 00:17:367506 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167507 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7508 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167509
[email protected]f7022f32014-08-21 16:32:197510 r->Start();
[email protected]5f714132014-03-26 10:41:167511 base::RunLoop().Run();
7512
maksim.sisovb53724b52016-09-16 05:30:507513 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307514
7515 // The redirect should have been rejected before reporting it to the caller.
7516 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:167517 }
7518}
7519
[email protected]5f714132014-03-26 10:41:167520// Redirects from an URL with fragment to an unsafe URL with fragment should
7521// be allowed, and the reference fragment of the target URL should be preserved.
7522TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:557523 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167524
tommycli59a63432015-11-06 00:10:557525 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:167526 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7527 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7528
7529 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7530 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7531
7532 TestDelegate d;
7533 {
rhalavatib7bd7c792017-04-27 05:25:167534 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7535 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167536
[email protected]f7022f32014-08-21 16:32:197537 r->Start();
[email protected]5f714132014-03-26 10:41:167538 base::RunLoop().Run();
7539
[email protected]f7022f32014-08-21 16:32:197540 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507541 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197542 EXPECT_EQ(original_url, r->original_url());
7543 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:167544 }
7545}
7546
7547// When a delegate has specified a safe redirect URL, but it does not match the
7548// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:147549TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:557550 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167551
tommycli59a63432015-11-06 00:10:557552 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167553 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:557554 GURL redirect_url(http_test_server()->GetURL("/target"));
7555 GURL expected_redirect_url(
7556 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167557
7558 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7559 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7560
7561 TestDelegate d;
7562 {
rhalavatib7bd7c792017-04-27 05:25:167563 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7564 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167565
[email protected]f7022f32014-08-21 16:32:197566 r->Start();
[email protected]5f714132014-03-26 10:41:167567 base::RunLoop().Run();
7568
[email protected]f7022f32014-08-21 16:32:197569 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507570 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197571 EXPECT_EQ(original_url, r->original_url());
7572 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:167573 }
7574}
7575
[email protected]f878230e2014-04-03 15:36:147576// When a delegate has specified a safe redirect URL, assume that the redirect
7577// URL should not be changed. In particular, the reference fragment should not
7578// be modified.
7579TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557580 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147581
tommycli59a63432015-11-06 00:10:557582 GURL original_url(
7583 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:147584 GURL redirect_url("data:text/html,expect-no-reference-fragment");
7585
7586 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7587 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
7588
7589 TestDelegate d;
7590 {
rhalavatib7bd7c792017-04-27 05:25:167591 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7592 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147593
[email protected]f7022f32014-08-21 16:32:197594 r->Start();
[email protected]f878230e2014-04-03 15:36:147595 base::RunLoop().Run();
7596
[email protected]f7022f32014-08-21 16:32:197597 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507598 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197599 EXPECT_EQ(original_url, r->original_url());
7600 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147601 }
7602}
7603
7604// When a URLRequestRedirectJob is created, the redirection must be followed and
7605// the reference fragment of the target URL must not be modified.
7606TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557607 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147608
tommycli59a63432015-11-06 00:10:557609 GURL original_url(
7610 http_test_server()->GetURL("/original#should-not-be-appended"));
7611 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:147612
7613 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167614 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7615 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147616
danakj8522a25b2016-04-16 00:17:367617 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197618 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:427619 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7620 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:147621
[email protected]f7022f32014-08-21 16:32:197622 r->Start();
[email protected]f878230e2014-04-03 15:36:147623 base::RunLoop().Run();
7624
maksim.sisovb53724b52016-09-16 05:30:507625 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197626 EXPECT_EQ(original_url, r->original_url());
7627 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147628}
7629
lizeb5120f6dc2016-02-19 09:29:447630TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
7631 ASSERT_TRUE(http_test_server()->Start());
7632
7633 const std::string referrer("foobar://totally.legit.referrer");
7634 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367635 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167636 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7637 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:447638 req->SetReferrer(referrer);
7639 req->Start();
7640 base::RunLoop().Run();
7641
7642 EXPECT_EQ(std::string("None"), d.data_received());
7643}
7644
[email protected]316c1e5e2012-09-12 15:17:447645TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:557646 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447647
7648 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367649 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167650 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7651 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197652 req->SetReferrer("http://user:[email protected]/");
7653 req->Start();
[email protected]255620da2013-08-19 13:14:297654 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447655
7656 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
7657}
7658
[email protected]99ecf6e2013-04-10 22:46:137659TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:557660 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137661
7662 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367663 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167664 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7665 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197666 req->SetReferrer("http://foo.com/test#fragment");
7667 req->Start();
[email protected]255620da2013-08-19 13:14:297668 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:137669
7670 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
7671}
7672
7673TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:557674 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137675
7676 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367677 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167678 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7679 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197680 req->SetReferrer("http://foo.com/test#fragment");
7681 req->SetReferrer("");
7682 req->Start();
[email protected]255620da2013-08-19 13:14:297683 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:137684
7685 EXPECT_EQ(std::string("None"), d.data_received());
7686}
7687
[email protected]316c1e5e2012-09-12 15:17:447688TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:557689 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447690
7691 TestDelegate d;
7692 {
7693 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:367694 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167695 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7696 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197697 req->Start();
[email protected]255620da2013-08-19 13:14:297698 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447699
7700 EXPECT_EQ(1, d.response_started_count());
7701 EXPECT_EQ(0, d.bytes_received());
7702 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507703 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447704 }
7705}
7706
7707TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:557708 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447709
7710 TestDelegate d;
7711 {
7712 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:557713 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:167714 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7715 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047716
[email protected]f7022f32014-08-21 16:32:197717 req->Start();
[email protected]255620da2013-08-19 13:14:297718 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447719
7720 EXPECT_EQ(1, d.received_redirect_count());
7721
[email protected]f7022f32014-08-21 16:32:197722 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:297723 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447724
7725 EXPECT_EQ(1, d.response_started_count());
7726 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507727 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447728
[email protected]6cdfd7f2013-02-08 20:40:157729 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:447730 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477731 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:447732 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7733
7734 std::string contents;
[email protected]82f84b92013-08-30 18:23:507735 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:447736 EXPECT_EQ(contents, d.data_received());
7737 }
7738}
7739
[email protected]79e1fd62013-06-20 06:50:047740TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:557741 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:047742
7743 TestDelegate d;
7744 {
7745 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:557746 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:167747 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7748 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047749
7750 EXPECT_FALSE(d.have_full_request_headers());
7751
[email protected]f7022f32014-08-21 16:32:197752 req->Start();
[email protected]255620da2013-08-19 13:14:297753 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:047754
7755 EXPECT_EQ(1, d.received_redirect_count());
7756 EXPECT_TRUE(d.have_full_request_headers());
7757 CheckFullRequestHeaders(d.full_request_headers(), test_url);
7758 d.ClearFullRequestHeaders();
7759
[email protected]f7022f32014-08-21 16:32:197760 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:297761 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:047762
tommycli59a63432015-11-06 00:10:557763 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:047764 EXPECT_EQ(1, d.response_started_count());
7765 EXPECT_TRUE(d.have_full_request_headers());
7766 CheckFullRequestHeaders(d.full_request_headers(), target_url);
7767 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507768 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:047769
7770 base::FilePath path;
7771 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477772 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:047773 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7774
7775 std::string contents;
[email protected]82f84b92013-08-30 18:23:507776 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:047777 EXPECT_EQ(contents, d.data_received());
7778 }
7779}
7780
[email protected]316c1e5e2012-09-12 15:17:447781TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:557782 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447783
7784 TestDelegate d;
7785 {
7786 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:367787 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167788 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7789 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197790 req->Start();
[email protected]255620da2013-08-19 13:14:297791 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447792
7793 EXPECT_EQ(1, d.received_redirect_count());
7794
[email protected]f7022f32014-08-21 16:32:197795 req->Cancel();
[email protected]255620da2013-08-19 13:14:297796 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447797
7798 EXPECT_EQ(1, d.response_started_count());
7799 EXPECT_EQ(0, d.bytes_received());
7800 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507801 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447802 }
7803}
7804
7805TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:557806 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447807
[email protected]3b23a222013-05-15 21:33:257808 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:447809 {
7810 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367811 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557812 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167813 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447814 HttpRequestHeaders headers;
7815 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197816 req->SetExtraRequestHeaders(headers);
7817 req->Start();
[email protected]255620da2013-08-19 13:14:297818 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:257819
7820 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197821 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257822 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447823 }
7824
[email protected]3b23a222013-05-15 21:33:257825 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:447826 {
7827 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367828 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557829 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167830 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447831 HttpRequestHeaders headers;
7832 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197833 req->SetExtraRequestHeaders(headers);
7834 req->Start();
[email protected]255620da2013-08-19 13:14:297835 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447836
[email protected]f7022f32014-08-21 16:32:197837 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257838
7839 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197840 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257841 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:447842 }
7843
[email protected]3b23a222013-05-15 21:33:257844 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:447845 {
7846 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367847 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557848 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167849 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447850 HttpRequestHeaders headers;
7851 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:197852 req->SetExtraRequestHeaders(headers);
7853 req->Start();
[email protected]255620da2013-08-19 13:14:297854 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447855
[email protected]f7022f32014-08-21 16:32:197856 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257857
7858 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197859 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257860 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447861 }
7862}
7863
7864TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:557865 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447866
7867 // populate the cache
7868 {
7869 TestDelegate d;
7870 d.set_credentials(AuthCredentials(kUser, kSecret));
7871
danakj8522a25b2016-04-16 00:17:367872 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167873 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7874 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197875 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447876
[email protected]255620da2013-08-19 13:14:297877 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447878
7879 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7880 }
7881
7882 // repeat request with end-to-end validation. since auth-basic results in a
7883 // cachable page, we expect this test to result in a 304. in which case, the
7884 // response should be fetched from the cache.
7885 {
7886 TestDelegate d;
7887 d.set_credentials(AuthCredentials(kUser, kSecret));
7888
danakj8522a25b2016-04-16 00:17:367889 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167890 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7891 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197892 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7893 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447894
[email protected]255620da2013-08-19 13:14:297895 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447896
7897 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7898
7899 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197900 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:447901 }
7902}
7903
7904// Check that Set-Cookie headers in 401 responses are respected.
7905// http://crbug.com/6450
7906TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:557907 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447908
7909 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:557910 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:447911
7912 // Request a page that will give a 401 containing a Set-Cookie header.
7913 // Verify that when the transaction is restarted, it includes the new cookie.
7914 {
[email protected]ceefd7fd2012-11-29 00:36:247915 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447916 TestURLRequestContext context(true);
7917 context.set_network_delegate(&network_delegate);
7918 context.Init();
7919
7920 TestDelegate d;
7921 d.set_credentials(AuthCredentials(kUser, kSecret));
7922
danakj8522a25b2016-04-16 00:17:367923 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:167924 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
7925 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197926 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447927
[email protected]255620da2013-08-19 13:14:297928 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447929
7930 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7931
7932 // Make sure we sent the cookie in the restarted transaction.
7933 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7934 != std::string::npos);
7935 }
7936
7937 // Same test as above, except this time the restart is initiated earlier
7938 // (without user intervention since identity is embedded in the URL).
7939 {
[email protected]ceefd7fd2012-11-29 00:36:247940 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447941 TestURLRequestContext context(true);
7942 context.set_network_delegate(&network_delegate);
7943 context.Init();
7944
7945 TestDelegate d;
7946
7947 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:187948 replacements.SetUsernameStr("user2");
7949 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:447950 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
7951
rhalavatib7bd7c792017-04-27 05:25:167952 std::unique_ptr<URLRequest> r(context.CreateRequest(
7953 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197954 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447955
[email protected]255620da2013-08-19 13:14:297956 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447957
7958 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
7959
7960 // Make sure we sent the cookie in the restarted transaction.
7961 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7962 != std::string::npos);
7963 }
7964}
7965
[email protected]58e32bb2013-01-21 18:23:257966// Tests that load timing works as expected with auth and the cache.
7967TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:557968 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:257969
7970 // populate the cache
7971 {
7972 TestDelegate d;
7973 d.set_credentials(AuthCredentials(kUser, kSecret));
7974
danakj8522a25b2016-04-16 00:17:367975 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167976 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7977 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197978 r->Start();
[email protected]58e32bb2013-01-21 18:23:257979
[email protected]255620da2013-08-19 13:14:297980 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257981
7982 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7983
7984 LoadTimingInfo load_timing_info_before_auth;
7985 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
7986 &load_timing_info_before_auth));
7987 TestLoadTimingNotReused(load_timing_info_before_auth,
7988 CONNECT_TIMING_HAS_DNS_TIMES);
7989
7990 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197991 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257992 // The test server does not support keep alive sockets, so the second
7993 // request with auth should use a new socket.
7994 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7995 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7996 load_timing_info.socket_log_id);
7997 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7998 load_timing_info.connect_timing.connect_start);
7999 }
8000
[email protected]3b23a222013-05-15 21:33:258001 // Repeat request with end-to-end validation. Since auth-basic results in a
8002 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258003 // response should be fetched from the cache.
8004 {
8005 TestDelegate d;
8006 d.set_credentials(AuthCredentials(kUser, kSecret));
8007
danakj8522a25b2016-04-16 00:17:368008 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168009 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8010 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198011 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8012 r->Start();
[email protected]58e32bb2013-01-21 18:23:258013
[email protected]255620da2013-08-19 13:14:298014 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:258015
8016 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8017
8018 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198019 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258020
[email protected]3b23a222013-05-15 21:33:258021 // Since there was a request that went over the wire, the load timing
8022 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258023 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198024 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258025 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258026 }
8027}
8028
[email protected]316c1e5e2012-09-12 15:17:448029// In this test, we do a POST which the server will 302 redirect.
8030// The subsequent transaction should use GET, and should not send the
8031// Content-Type header.
8032// http://code.google.com/p/chromium/issues/detail?id=843
8033TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558034 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448035
8036 const char kData[] = "hello world";
8037
8038 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368039 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168040 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8041 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198042 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078043 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448044
8045 // Set headers (some of which are specific to the POST).
8046 HttpRequestHeaders headers;
8047 headers.AddHeadersFromString(
8048 "Content-Type: multipart/form-data; "
8049 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
8050 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
8051 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
8052 "Accept-Language: en-US,en\r\n"
8053 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
8054 "Content-Length: 11\r\n"
8055 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198056 req->SetExtraRequestHeaders(headers);
8057 req->Start();
[email protected]255620da2013-08-19 13:14:298058 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448059
8060 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198061 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448062 EXPECT_EQ("text/html", mime_type);
8063
8064 const std::string& data = d.data_received();
8065
8066 // Check that the post-specific headers were stripped:
8067 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8068 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
[email protected]316c1e5e2012-09-12 15:17:448069
8070 // These extra request headers should not have been stripped.
8071 EXPECT_TRUE(ContainsString(data, "Accept:"));
8072 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8073 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
Yutaka Hirano322fef872017-08-09 08:11:438074 EXPECT_TRUE(ContainsString(data, "Origin: http://localhost:1337"));
[email protected]316c1e5e2012-09-12 15:17:448075}
8076
jww5fe460ff2015-03-28 00:22:518077// The following tests check that we handle mutating the request for HTTP
8078// redirects as expected.
8079// See https://crbug.com/56373, https://crbug.com/102130, and
8080// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448081
8082TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558083 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448084
tommycli59a63432015-11-06 00:10:558085 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518086 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558087 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448088
8089 HTTPRedirectMethodTest(url, "POST", "GET", true);
8090 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8091 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518092
8093 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8094 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano322fef872017-08-09 08:11:438095 HTTPRedirectOriginHeaderTest(url, "POST", "GET", url.GetOrigin().spec());
8096 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET", "null");
[email protected]316c1e5e2012-09-12 15:17:448097}
8098
8099TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558100 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448101
tommycli59a63432015-11-06 00:10:558102 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518103 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558104 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448105
8106 HTTPRedirectMethodTest(url, "POST", "GET", true);
8107 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8108 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518109
8110 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8111 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano322fef872017-08-09 08:11:438112 HTTPRedirectOriginHeaderTest(url, "POST", "GET", url.GetOrigin().spec());
8113 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET", "null");
[email protected]316c1e5e2012-09-12 15:17:448114}
8115
8116TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558117 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448118
tommycli59a63432015-11-06 00:10:558119 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518120 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558121 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448122
8123 HTTPRedirectMethodTest(url, "POST", "GET", true);
8124 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8125 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518126
8127 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8128 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano322fef872017-08-09 08:11:438129 HTTPRedirectOriginHeaderTest(url, "POST", "GET", url.GetOrigin().spec());
8130 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET", "null");
[email protected]316c1e5e2012-09-12 15:17:448131}
8132
8133TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558134 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448135
tommycli59a63432015-11-06 00:10:558136 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518137 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558138 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448139
8140 HTTPRedirectMethodTest(url, "POST", "POST", true);
8141 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8142 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518143
8144 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8145 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8146 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8147 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:448148}
8149
[email protected]0a17aab32014-04-24 03:32:378150TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:558151 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378152
tommycli59a63432015-11-06 00:10:558153 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:518154 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558155 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:378156
8157 HTTPRedirectMethodTest(url, "POST", "POST", true);
8158 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8159 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518160
8161 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8162 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8163 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8164 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:378165}
8166
8167// Make sure that 308 responses without bodies are not treated as redirects.
8168// Certain legacy apis that pre-date the response code expect this behavior
8169// (Like Google Drive).
8170TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:558171 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378172
8173 TestDelegate d;
tommycli59a63432015-11-06 00:10:558174 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:378175
rhalavatib7bd7c792017-04-27 05:25:168176 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
8177 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:378178
[email protected]f7022f32014-08-21 16:32:198179 request->Start();
[email protected]0a17aab32014-04-24 03:32:378180 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:508181 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:378182 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198183 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:378184 EXPECT_EQ("This is not a redirect.", d.data_received());
8185}
8186
[email protected]f878230e2014-04-03 15:36:148187TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558188 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148189
tommycli59a63432015-11-06 00:10:558190 GURL original_url(
8191 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8192 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148193
8194 TestDelegate d;
8195 {
rhalavatib7bd7c792017-04-27 05:25:168196 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8197 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148198
[email protected]f7022f32014-08-21 16:32:198199 r->Start();
[email protected]f878230e2014-04-03 15:36:148200 base::RunLoop().Run();
8201
[email protected]f7022f32014-08-21 16:32:198202 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508203 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198204 EXPECT_EQ(original_url, r->original_url());
8205 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148206 }
8207}
8208
[email protected]cba24642014-08-15 20:49:598209TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558210 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598211
tommycli59a63432015-11-06 00:10:558212 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598213 GURL first_party_url("http://example.com");
8214
8215 TestDelegate d;
8216 {
rhalavatib7bd7c792017-04-27 05:25:168217 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8218 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468219 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:598220
[email protected]f7022f32014-08-21 16:32:198221 r->Start();
[email protected]cba24642014-08-15 20:49:598222 base::RunLoop().Run();
8223
[email protected]f7022f32014-08-21 16:32:198224 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508225 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468226 EXPECT_EQ(first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598227 }
8228}
8229
8230TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558231 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598232
tommycli59a63432015-11-06 00:10:558233 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598234 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:558235 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:598236
8237 TestDelegate d;
8238 {
rhalavatib7bd7c792017-04-27 05:25:168239 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8240 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468241 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:198242 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:598243 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8244
[email protected]f7022f32014-08-21 16:32:198245 r->Start();
[email protected]cba24642014-08-15 20:49:598246 base::RunLoop().Run();
8247
[email protected]f7022f32014-08-21 16:32:198248 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508249 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468250 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598251 }
8252}
8253
[email protected]316c1e5e2012-09-12 15:17:448254TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:558255 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448256
8257 const char kData[] = "hello world";
8258
8259 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368260 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168261 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8262 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198263 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078264 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448265 HttpRequestHeaders headers;
8266 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:518267 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198268 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448269
danakj8522a25b2016-04-16 00:17:368270 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558271 req.get(), &default_network_delegate_,
8272 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428273 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8274 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448275
[email protected]f7022f32014-08-21 16:32:198276 req->Start();
[email protected]255620da2013-08-19 13:14:298277 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198278 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:448279}
8280
8281TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:558282 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448283
8284 const char kData[] = "hello world";
8285
8286 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368287 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168288 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8289 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198290 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078291 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448292 HttpRequestHeaders headers;
8293 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:518294 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198295 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448296
danakj8522a25b2016-04-16 00:17:368297 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558298 req.get(), &default_network_delegate_,
8299 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:098300 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:428301 "Very Good Reason"));
8302 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448303
[email protected]f7022f32014-08-21 16:32:198304 req->Start();
[email protected]255620da2013-08-19 13:14:298305 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198306 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:448307 EXPECT_EQ(kData, d.data_received());
8308}
8309
8310// Check that default A-L header is sent.
8311TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558312 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448313
[email protected]8790210c2013-12-02 05:29:538314 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:248315 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448316 TestURLRequestContext context(true);
8317 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:438318 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448319 context.Init();
8320
8321 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368322 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558323 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168324 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198325 req->Start();
[email protected]255620da2013-08-19 13:14:298326 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448327 EXPECT_EQ("en", d.data_received());
8328}
8329
8330// Check that an empty A-L header is not sent. http://crbug.com/77365.
8331TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558332 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448333
[email protected]8790210c2013-12-02 05:29:538334 std::string empty_string; // Avoid most vexing parse on line below.
8335 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:248336 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448337 TestURLRequestContext context(true);
8338 context.set_network_delegate(&network_delegate);
8339 context.Init();
8340 // We override the language after initialization because empty entries
8341 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:438342 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448343
8344 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368345 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558346 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168347 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198348 req->Start();
[email protected]255620da2013-08-19 13:14:298349 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448350 EXPECT_EQ("None", d.data_received());
8351}
8352
8353// Check that if request overrides the A-L header, the default is not appended.
8354// See http://crbug.com/20894
8355TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558356 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448357
8358 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368359 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558360 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168361 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448362 HttpRequestHeaders headers;
8363 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:198364 req->SetExtraRequestHeaders(headers);
8365 req->Start();
[email protected]255620da2013-08-19 13:14:298366 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448367 EXPECT_EQ(std::string("ru"), d.data_received());
8368}
8369
8370// Check that default A-E header is sent.
8371TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558372 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448373
8374 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368375 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558376 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168377 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448378 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:198379 req->SetExtraRequestHeaders(headers);
8380 req->Start();
[email protected]255620da2013-08-19 13:14:298381 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448382 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
8383}
8384
8385// Check that if request overrides the A-E header, the default is not appended.
8386// See http://crbug.com/47381
8387TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558388 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448389
8390 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368391 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558392 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168393 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448394 HttpRequestHeaders headers;
8395 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:198396 req->SetExtraRequestHeaders(headers);
8397 req->Start();
[email protected]255620da2013-08-19 13:14:298398 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448399 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
8400 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
8401}
8402
[email protected]84f05432013-03-15 01:00:128403// Check that setting the A-C header sends the proper header.
8404TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:558405 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448406
8407 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368408 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558409 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:168410 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448411 HttpRequestHeaders headers;
8412 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:198413 req->SetExtraRequestHeaders(headers);
8414 req->Start();
[email protected]255620da2013-08-19 13:14:298415 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448416 EXPECT_EQ(std::string("koi-8r"), d.data_received());
8417}
8418
8419// Check that default User-Agent header is sent.
8420TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:558421 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448422
8423 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368424 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558425 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168426 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198427 req->Start();
[email protected]255620da2013-08-19 13:14:298428 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198429 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:378430 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448431}
8432
8433// Check that if request overrides the User-Agent header,
8434// the default is not appended.
marqf14fff8d2015-12-02 15:52:298435// TODO(crbug.com/564656) This test is flaky on iOS.
8436#if defined(OS_IOS)
8437#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
8438#else
8439#define MAYBE_OverrideUserAgent OverrideUserAgent
8440#endif
8441TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:558442 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448443
8444 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368445 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558446 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168447 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448448 HttpRequestHeaders headers;
8449 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:198450 req->SetExtraRequestHeaders(headers);
8451 req->Start();
[email protected]255620da2013-08-19 13:14:298452 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:358453 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448454}
8455
[email protected]ee4c30d2012-11-07 15:08:438456// Check that a NULL HttpUserAgentSettings causes the corresponding empty
8457// User-Agent header to be sent but does not send the Accept-Language and
8458// Accept-Charset headers.
8459TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:558460 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:438461
[email protected]ceefd7fd2012-11-29 00:36:248462 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:438463 TestURLRequestContext context(true);
8464 context.set_network_delegate(&network_delegate);
8465 context.Init();
8466 // We override the HttpUserAgentSettings after initialization because empty
8467 // entries get overridden by Init().
8468 context.set_http_user_agent_settings(NULL);
8469
8470 struct {
8471 const char* request;
8472 const char* expected_response;
tommycli59a63432015-11-06 00:10:558473 } tests[] = {{"/echoheader?Accept-Language", "None"},
8474 {"/echoheader?Accept-Charset", "None"},
8475 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:438476
viettrungluue4a8b882014-10-16 06:17:388477 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:438478 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368479 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168480 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
8481 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198482 req->Start();
[email protected]255620da2013-08-19 13:14:298483 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:438484 EXPECT_EQ(tests[i].expected_response, d.data_received())
8485 << " Request = \"" << tests[i].request << "\"";
8486 }
8487}
8488
[email protected]5033ab82013-03-22 20:17:468489// Make sure that URLRequest passes on its priority updates to
8490// newly-created jobs after the first one.
8491TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:558492 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:468493
8494 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368495 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168496 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8497 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198498 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:468499
danakj8522a25b2016-04-16 00:17:368500 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558501 req.get(), &default_network_delegate_,
8502 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428503 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8504 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:468505
[email protected]f7022f32014-08-21 16:32:198506 req->SetPriority(LOW);
8507 req->Start();
8508 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:468509
mmenkeed0498b2015-12-08 23:20:428510 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:368511 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:428512 req.get(), &default_network_delegate_, &job_priority));
8513 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:468514
8515 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:298516 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:428517 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:468518}
8519
[email protected]80abdad2014-03-15 00:20:548520// Check that creating a network request while entering/exiting suspend mode
8521// fails as it should. This is the only case where an HttpTransactionFactory
8522// does not return an HttpTransaction.
8523TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
8524 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:368525 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:178526 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:548527 network_layer->OnSuspend();
8528
dchengc7eeda422015-12-26 03:56:488529 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:038530 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:278531 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:548532
8533 TestURLRequestContext context(true);
8534 context.set_http_transaction_factory(&http_cache);
8535 context.Init();
8536
8537 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368538 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:168539 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
8540 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198541 req->Start();
[email protected]80abdad2014-03-15 00:20:548542 base::RunLoop().Run();
8543
8544 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:508545 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:548546}
8547
mmenke2281f3762015-11-02 20:38:178548namespace {
[email protected]80abdad2014-03-15 00:20:548549
mmenke2281f3762015-11-02 20:38:178550// HttpTransactionFactory that synchronously fails to create transactions.
8551class FailingHttpTransactionFactory : public HttpTransactionFactory {
8552 public:
8553 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
8554 : network_session_(network_session) {}
8555
8556 ~FailingHttpTransactionFactory() override {}
8557
8558 // HttpTransactionFactory methods:
8559 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:368560 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:178561 return ERR_FAILED;
8562 }
8563
8564 HttpCache* GetCache() override { return nullptr; }
8565
8566 HttpNetworkSession* GetSession() override { return network_session_; }
8567
8568 private:
8569 HttpNetworkSession* network_session_;
8570
8571 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
8572};
8573
8574} // namespace
8575
8576// Check that when a request that fails to create an HttpTransaction can be
8577// cancelled while the failure notification is pending, and doesn't send two
8578// failure notifications.
8579//
8580// This currently only happens when in suspend mode and there's no cache, but
8581// just use a special HttpTransactionFactory, to avoid depending on those
8582// behaviors.
8583TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
8584 FailingHttpTransactionFactory http_transaction_factory(
8585 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:548586 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:178587 context.set_http_transaction_factory(&http_transaction_factory);
8588 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:548589 context.Init();
8590
8591 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368592 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:168593 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
8594 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:178595 // Don't send cookies (Collecting cookies is asynchronous, and need request to
8596 // try to create an HttpNetworkTransaction synchronously on start).
8597 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:198598 req->Start();
mmenke2281f3762015-11-02 20:38:178599 req->Cancel();
[email protected]80abdad2014-03-15 00:20:548600 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:178601 // Run pending error task, if there is one.
8602 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:548603
8604 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:178605 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:508606 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:178607
8608 // NetworkDelegate should see the cancellation, but not the error.
8609 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
8610 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:548611}
8612
ttuttlec0c828492015-05-15 01:25:558613TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:558614 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558615
8616 TestDelegate d;
tommycli59a63432015-11-06 00:10:558617 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:168618 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8619 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:558620
8621 req->Start();
8622 base::RunLoop().Run();
8623
8624 EXPECT_TRUE(req->response_info().network_accessed);
8625}
8626
8627TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:558628 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558629
8630 // Populate the cache.
8631 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368632 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168633 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
8634 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:558635 req->Start();
8636 base::RunLoop().Run();
8637
maksim.sisovb53724b52016-09-16 05:30:508638 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:558639 EXPECT_TRUE(req->response_info().network_accessed);
8640 EXPECT_FALSE(req->response_info().was_cached);
8641
tommycli59a63432015-11-06 00:10:558642 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
rhalavatib7bd7c792017-04-27 05:25:168643 DEFAULT_PRIORITY, &d,
8644 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:558645 req->Start();
8646 base::RunLoop().Run();
8647
maksim.sisovb53724b52016-09-16 05:30:508648 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:558649 EXPECT_FALSE(req->response_info().network_accessed);
8650 EXPECT_TRUE(req->response_info().was_cached);
8651}
8652
8653TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:558654 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558655
8656 TestDelegate d;
tommycli59a63432015-11-06 00:10:558657 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:168658 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8659 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:338660 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:558661
8662 req->Start();
8663 base::RunLoop().Run();
8664
8665 EXPECT_FALSE(req->response_info().network_accessed);
8666}
8667
rdsmithbf8c3c12016-11-18 18:16:248668// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:088669// correctly in the absence of contention.
8670TEST_F(URLRequestTestHTTP, ThrottledPriority) {
8671 ASSERT_TRUE(http_test_server()->Start());
8672
8673 TestDelegate d;
8674 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:168675 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8676 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:088677 req->Start();
8678 base::RunLoop().Run();
8679
8680 EXPECT_TRUE(req->status().is_success());
8681}
8682
rdsmithbf8c3c12016-11-18 18:16:248683// A class to hold state for responding to USER_NOTIFY callbacks from
8684// BlockingNetworkDelegate. It also accepts a RunLoop that will be
8685// signaled via QuitWhenIdle() when any request is blocked.
8686//
8687class NotificationCallbackHandler {
8688 public:
8689 // Default constructed object doesn't block anything.
8690 NotificationCallbackHandler() : run_loop_(nullptr) {}
8691
8692 void AddURLRequestToBlockList(const URLRequest* request) {
8693 requests_to_block_.insert(request);
8694 }
8695
8696 Error ShouldBlockRequest(const CompletionCallback& callback,
8697 const URLRequest* request) {
8698 if (requests_to_block_.find(request) == requests_to_block_.end()) {
8699 return OK;
8700 }
8701
8702 DCHECK(blocked_callbacks_.find(request) == blocked_callbacks_.end());
8703 blocked_callbacks_[request] = callback;
8704 if (run_loop_ && blocked_callbacks_.size() == requests_to_block_.size())
8705 run_loop_->QuitWhenIdle();
8706 return ERR_IO_PENDING;
8707 }
8708
8709 // Erases object's memory of blocked callbacks as a side effect.
8710 void GetBlockedCallbacks(
8711 std::map<const URLRequest*, CompletionCallback>* blocked_callbacks) {
8712 blocked_callbacks_.swap(*blocked_callbacks);
8713 }
8714
8715 // Set a RunLoop that, if non-null, will be signaled if any request
8716 // is blocked. It is the callers responsibility to make sure the
8717 // passed object lives past the destruction of this class or
8718 // next call to SetRunLoop().
8719 void SetRunLoop(base::RunLoop* run_loop) { run_loop_ = run_loop; }
8720
8721 private:
8722 std::set<const URLRequest*> requests_to_block_;
8723 std::map<const URLRequest*, CompletionCallback> blocked_callbacks_;
8724
8725 base::RunLoop* run_loop_;
8726
8727 DISALLOW_COPY_AND_ASSIGN(NotificationCallbackHandler);
8728};
8729
8730TEST_F(URLRequestTestHTTP, MultiThrottledPriority) {
8731 ASSERT_TRUE(http_test_server()->Start());
8732
8733 base::RunLoop run_until_request_blocked;
8734
8735 NotificationCallbackHandler notification_handler;
8736 notification_handler.SetRunLoop(&run_until_request_blocked);
8737 BlockingNetworkDelegate network_delegate(
8738 BlockingNetworkDelegate::USER_NOTIFY);
8739 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
8740 network_delegate.set_notification_callback(
8741 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
8742 // Both objects are owned by this function, and
8743 // |*network_delegate| will be destroyed first, so
8744 // it's safe to pass it an unretained pointer.
8745 base::Unretained(&notification_handler)));
8746
8747 TestURLRequestContext context(true);
8748 context.set_network_delegate(&network_delegate);
8749 context.Init();
8750
8751 // Use different test URLs to make sure all three requests turn into
8752 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
8753 // the requests may be waited on separately.
8754 TestDelegate d1;
rhalavatib7bd7c792017-04-27 05:25:168755 std::unique_ptr<URLRequest> req1(
8756 context.CreateRequest(http_test_server()->GetURL("/echoall/l"), THROTTLED,
8757 &d1, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248758 notification_handler.AddURLRequestToBlockList(req1.get());
8759
8760 TestDelegate d2;
rhalavatib7bd7c792017-04-27 05:25:168761 std::unique_ptr<URLRequest> req2(
8762 context.CreateRequest(http_test_server()->GetURL("/echoall/2"), THROTTLED,
8763 &d2, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248764 notification_handler.AddURLRequestToBlockList(req2.get());
8765
8766 TestDelegate d3;
rhalavatib7bd7c792017-04-27 05:25:168767 std::unique_ptr<URLRequest> req3(
8768 context.CreateRequest(http_test_server()->GetURL("/echoall/3"), THROTTLED,
8769 &d3, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248770 req1->Start();
8771 req2->Start();
8772 req3->Start();
8773 run_until_request_blocked.Run();
8774 notification_handler.SetRunLoop(nullptr);
8775
8776 // The first two requests should be blocked based on the notification
8777 // callback, and their status should have blocked the third request
8778 // through throttling.
8779 EXPECT_TRUE(req1->status().is_io_pending());
8780 EXPECT_TRUE(req2->status().is_io_pending());
8781 EXPECT_TRUE(req3->status().is_io_pending());
8782
8783 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
8784 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8785 ASSERT_EQ(2u, blocked_callbacks.size());
8786 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
8787 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
8788
8789 // Unblocking one of the requests blocked on the notification callback
8790 // should let it complete, which should then let the third request
8791 // complete. Unblock the second request, then wait for the third
8792 // request to complete.
8793 // TODO(rdsmith): Find something to wait on other than the third
8794 // requests completion; if there's a bug in throttling, that will
8795 // result in this test hanging rather than failing quickly.
8796 d1.set_quit_on_complete(false);
8797 d2.set_quit_on_complete(false);
8798 d3.set_quit_on_complete(true);
8799 blocked_callbacks[req2.get()].Run(OK);
8800 base::RunLoop().Run();
8801
8802 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8803 EXPECT_EQ(0u, blocked_callbacks.size());
8804 EXPECT_TRUE(req1->status().is_io_pending());
8805 // req3 is only unblocked after req2 completes, so req2's
8806 // success is guaranteed at this point in the function.
8807 EXPECT_EQ(URLRequestStatus::SUCCESS, req2->status().status());
8808 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8809}
8810
8811// Confirm that failing a request unblocks following requests.
8812TEST_F(URLRequestTestHTTP, ThrottledFailure) {
8813 ASSERT_TRUE(http_test_server()->Start());
8814
8815 base::RunLoop run_until_request_blocked;
8816
8817 NotificationCallbackHandler notification_handler;
8818 notification_handler.SetRunLoop(&run_until_request_blocked);
8819 BlockingNetworkDelegate network_delegate(
8820 BlockingNetworkDelegate::USER_NOTIFY);
8821 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
8822 network_delegate.set_notification_callback(
8823 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
8824 // Both objects are owned by this function, and
8825 // |*network_delegate| will be destroyed first, so
8826 // it's safe to pass it an unretained pointer.
8827 base::Unretained(&notification_handler)));
8828
8829 TestURLRequestContext context(true);
8830 context.set_network_delegate(&network_delegate);
8831 context.Init();
8832
8833 // Use different test URLs to make sure all three requests turn into
8834 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
8835 // the requests may be waited on separately.
8836 TestDelegate d1;
rhalavatib7bd7c792017-04-27 05:25:168837 std::unique_ptr<URLRequest> req1(
8838 context.CreateRequest(http_test_server()->GetURL("/echoall/l"), THROTTLED,
8839 &d1, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248840 notification_handler.AddURLRequestToBlockList(req1.get());
8841
8842 TestDelegate d2;
rhalavatib7bd7c792017-04-27 05:25:168843 std::unique_ptr<URLRequest> req2(
8844 context.CreateRequest(http_test_server()->GetURL("/echoall/2"), THROTTLED,
8845 &d2, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248846 notification_handler.AddURLRequestToBlockList(req2.get());
8847
8848 TestDelegate d3;
rhalavatib7bd7c792017-04-27 05:25:168849 std::unique_ptr<URLRequest> req3(
8850 context.CreateRequest(http_test_server()->GetURL("/echoall/3"), THROTTLED,
8851 &d3, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248852 req1->Start();
8853 req2->Start();
8854 req3->Start();
8855 run_until_request_blocked.Run();
8856 notification_handler.SetRunLoop(nullptr);
8857
8858 // The first two requests should be blocked based on the notification
8859 // callback, and their status should have blocked the third request
8860 // through throttling.
8861 EXPECT_TRUE(req1->status().is_io_pending());
8862 EXPECT_TRUE(req2->status().is_io_pending());
8863 EXPECT_TRUE(req3->status().is_io_pending());
8864
8865 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
8866 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8867 ASSERT_EQ(2u, blocked_callbacks.size());
8868 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
8869 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
8870
8871 // Confirm canceling one of the outstanding requests allows the
8872 // blocked request to complete.
8873
8874 // TODO(rdsmith): Find something to wait on other than the third
8875 // requests completion; if there's a bug in throttling, that will
8876 // result in this test hanging rather than failing quickly.
8877 d1.set_quit_on_complete(false);
8878 d2.set_quit_on_complete(false);
8879 d3.set_quit_on_complete(true);
8880 req2->Cancel();
8881 base::RunLoop().Run();
8882
8883 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8884 EXPECT_EQ(0u, blocked_callbacks.size());
8885 EXPECT_TRUE(req1->status().is_io_pending());
8886 EXPECT_EQ(URLRequestStatus::CANCELED, req2->status().status());
8887 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8888}
8889
8890TEST_F(URLRequestTestHTTP, ThrottledRepriUnblock) {
8891 ASSERT_TRUE(http_test_server()->Start());
8892
8893 base::RunLoop run_until_request_blocked;
8894
8895 NotificationCallbackHandler notification_handler;
8896 notification_handler.SetRunLoop(&run_until_request_blocked);
8897 BlockingNetworkDelegate network_delegate(
8898 BlockingNetworkDelegate::USER_NOTIFY);
8899 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
8900 network_delegate.set_notification_callback(
8901 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
8902 // Both objects are owned by this function, and
8903 // |*network_delegate| will be destroyed first, so
8904 // it's safe to pass it an unretained pointer.
8905 base::Unretained(&notification_handler)));
8906
8907 TestURLRequestContext context(true);
8908 context.set_network_delegate(&network_delegate);
8909 context.Init();
8910
8911 // Use different test URLs to make sure all three requests turn into
8912 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
8913 // the requests may be waited on separately.
8914 TestDelegate d1;
rhalavatib7bd7c792017-04-27 05:25:168915 std::unique_ptr<URLRequest> req1(
8916 context.CreateRequest(http_test_server()->GetURL("/echoall/l"), THROTTLED,
8917 &d1, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248918 notification_handler.AddURLRequestToBlockList(req1.get());
8919
8920 TestDelegate d2;
rhalavatib7bd7c792017-04-27 05:25:168921 std::unique_ptr<URLRequest> req2(
8922 context.CreateRequest(http_test_server()->GetURL("/echoall/2"), THROTTLED,
8923 &d2, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248924 notification_handler.AddURLRequestToBlockList(req2.get());
8925
8926 TestDelegate d3;
rhalavatib7bd7c792017-04-27 05:25:168927 std::unique_ptr<URLRequest> req3(
8928 context.CreateRequest(http_test_server()->GetURL("/echoall/3"), THROTTLED,
8929 &d3, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248930 req1->Start();
8931 req2->Start();
8932 req3->Start();
8933 run_until_request_blocked.Run();
8934 notification_handler.SetRunLoop(nullptr);
8935
8936 // The first two requests should be blocked based on the notification
8937 // callback, and their status should have blocked the third request
8938 // through throttling.
8939 EXPECT_TRUE(req1->status().is_io_pending());
8940 EXPECT_TRUE(req2->status().is_io_pending());
8941 EXPECT_TRUE(req3->status().is_io_pending());
8942
8943 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
8944 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8945 ASSERT_EQ(2u, blocked_callbacks.size());
8946 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
8947 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
8948
8949 // Confirm raising the priority of the third request allows it to complete.
8950
8951 // TODO(rdsmith): Find something to wait on other than the third
8952 // requests completion; if there's a bug in throttling, that will
8953 // result in this test hanging rather than failing quickly.
8954 d1.set_quit_on_complete(false);
8955 d2.set_quit_on_complete(false);
8956 d3.set_quit_on_complete(true);
8957 req3->SetPriority(IDLE);
8958 base::RunLoop().Run();
8959
8960 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8961 EXPECT_EQ(0u, blocked_callbacks.size());
8962 EXPECT_TRUE(req1->status().is_io_pending());
8963 EXPECT_TRUE(req2->status().is_io_pending());
8964 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8965}
8966
ricea3a1c71f2016-06-17 10:05:268967TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
8968 ASSERT_TRUE(http_test_server()->Start());
8969
8970 TestDelegate d;
8971 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168972 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
8973 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:268974 req->Start();
8975 base::RunLoop().Run();
8976
8977 EXPECT_EQ(5, req->GetRawBodyBytes());
8978}
8979
8980TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
8981 ASSERT_TRUE(http_test_server()->Start());
8982
8983 TestDelegate d;
8984 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168985 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
8986 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:268987 req->Start();
8988 base::RunLoop().Run();
8989
8990 EXPECT_EQ(30, req->GetRawBodyBytes());
8991}
8992
jamd3f5a3c2016-10-27 18:52:028993// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
8994// the delegate isn't called back synchronously.
8995TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
8996 ASSERT_TRUE(http_test_server()->Start());
8997 default_network_delegate_.set_before_start_transaction_fails();
8998
8999 TestDelegate d;
9000 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169001 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
9002 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:029003 req->Start();
9004 DCHECK(!d.response_completed());
9005 base::RunLoop().Run();
9006 DCHECK(d.response_completed());
9007 EXPECT_EQ(ERR_FAILED, d.request_status());
9008}
9009
bengr1bf8e942014-11-07 01:36:509010class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
9011 public:
9012 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
9013 // ideally remove the dependency on URLRequestTestJob, and maybe move these
9014 // tests into the factory tests.
9015 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
9016 }
9017
9018 void SetUpFactory() override {
9019 interceptor_ = new MockURLRequestInterceptor();
9020 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:369021 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:509022 }
9023
9024 MockURLRequestInterceptor* interceptor() const {
9025 return interceptor_;
9026 }
9027
9028 private:
9029 MockURLRequestInterceptor* interceptor_;
9030};
9031
9032TEST_F(URLRequestInterceptorTestHTTP,
9033 NetworkDelegateNotificationOnRedirectIntercept) {
9034 interceptor()->set_intercept_redirect(true);
9035 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
9036 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
9037
tommycli59a63432015-11-06 00:10:559038 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509039
9040 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369041 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169042 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
9043 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509044 req->Start();
9045 base::RunLoop().Run();
9046
9047 EXPECT_TRUE(interceptor()->did_intercept_redirect());
9048 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:509049 int status = d.request_status();
9050 EXPECT_EQ(OK, status);
9051 if (status == OK)
bengr1bf8e942014-11-07 01:36:509052 EXPECT_EQ(200, req->response_headers()->response_code());
9053
9054 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9055 EXPECT_EQ(1, d.response_started_count());
9056 EXPECT_EQ(0, d.received_redirect_count());
9057
9058 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009059 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509060 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
9061}
9062
9063TEST_F(URLRequestInterceptorTestHTTP,
9064 NetworkDelegateNotificationOnErrorIntercept) {
9065 // Intercept that error and respond with an OK response.
9066 interceptor()->set_intercept_final_response(true);
9067 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
9068 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
9069 default_network_delegate()->set_can_be_intercepted_on_error(true);
9070
tommycli59a63432015-11-06 00:10:559071 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509072
9073 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369074 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559075 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169076 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509077 req->set_method("GET");
9078 req->Start();
9079 base::RunLoop().Run();
9080
9081 EXPECT_TRUE(interceptor()->did_intercept_final());
9082
9083 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509084 int status = d.request_status();
9085 EXPECT_EQ(OK, status);
9086 if (status == OK)
bengr1bf8e942014-11-07 01:36:509087 EXPECT_EQ(200, req->response_headers()->response_code());
9088 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9089 EXPECT_EQ(1, d.response_started_count());
9090 EXPECT_EQ(0, d.received_redirect_count());
9091
9092 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009093 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509094 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9095}
9096
9097TEST_F(URLRequestInterceptorTestHTTP,
9098 NetworkDelegateNotificationOnResponseIntercept) {
9099 // Intercept that error and respond with an OK response.
9100 interceptor()->set_intercept_final_response(true);
9101
9102 // Intercept with a real URLRequestHttpJob.
9103 interceptor()->set_use_url_request_http_job(true);
9104
tommycli59a63432015-11-06 00:10:559105 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509106
9107 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369108 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169109 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9110 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509111 req->set_method("GET");
9112 req->Start();
9113 base::RunLoop().Run();
9114
9115 EXPECT_TRUE(interceptor()->did_intercept_final());
9116
9117 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509118 int status = d.request_status();
9119 EXPECT_EQ(OK, status);
9120 if (status == OK)
bengr1bf8e942014-11-07 01:36:509121 EXPECT_EQ(200, req->response_headers()->response_code());
9122 EXPECT_EQ("hello", d.data_received());
9123 EXPECT_EQ(1, d.response_started_count());
9124 EXPECT_EQ(0, d.received_redirect_count());
9125
9126 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009127 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509128 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9129}
9130
mkwst0c5eab872014-11-21 14:18:549131class URLRequestTestReferrerPolicy : public URLRequestTest {
9132 public:
9133 URLRequestTestReferrerPolicy() {}
9134
tommycli59a63432015-11-06 00:10:559135 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9136 origin_server_.reset(new EmbeddedTestServer(type));
9137 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9138 origin_server_->AddDefaultHandlers(
9139 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9140 } else {
9141 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9142 }
mkwst0c5eab872014-11-21 14:18:549143 ASSERT_TRUE(origin_server_->Start());
9144 }
9145
tommycli59a63432015-11-06 00:10:559146 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9147 net::EmbeddedTestServer::Type dest_type) {
9148 origin_server_.reset(new EmbeddedTestServer(origin_type));
9149 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9150 origin_server_->AddDefaultHandlers(
9151 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9152 } else {
9153 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9154 }
mkwst0c5eab872014-11-21 14:18:549155 ASSERT_TRUE(origin_server_->Start());
9156
tommycli59a63432015-11-06 00:10:559157 destination_server_.reset(new EmbeddedTestServer(dest_type));
9158 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9159 destination_server_->AddDefaultHandlers(
9160 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9161 } else {
9162 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9163 }
mkwst0c5eab872014-11-21 14:18:549164 ASSERT_TRUE(destination_server_->Start());
9165 }
9166
9167 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9168 const GURL& referrer,
9169 const GURL& expected) {
9170 // Create and execute the request: we'll only have a |destination_server_|
9171 // if the origins are meant to be distinct. Otherwise, we'll use the
9172 // |origin_server_| for both endpoints.
9173 GURL destination_url =
tommycli59a63432015-11-06 00:10:559174 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9175 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549176 GURL origin_url =
tommycli59a63432015-11-06 00:10:559177 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549178
9179 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:169180 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9181 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549182 req->set_referrer_policy(policy);
9183 req->SetReferrer(referrer.spec());
9184 req->Start();
9185 base::RunLoop().Run();
9186
9187 EXPECT_EQ(1, d.response_started_count());
9188 EXPECT_EQ(1, d.received_redirect_count());
9189 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509190 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549191 EXPECT_EQ(200, req->response_headers()->response_code());
9192
9193 EXPECT_EQ(expected.spec(), req->referrer());
9194 if (expected.is_empty())
9195 EXPECT_EQ("None", d.data_received());
9196 else
9197 EXPECT_EQ(expected.spec(), d.data_received());
9198 }
9199
tommycli59a63432015-11-06 00:10:559200 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:549201
9202 private:
danakj8522a25b2016-04-16 00:17:369203 std::unique_ptr<EmbeddedTestServer> origin_server_;
9204 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:549205};
9206
9207TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:559208 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:549209
estarkc8ccba82017-06-13 22:37:409210 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549211 VerifyReferrerAfterRedirect(
9212 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409213 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549214
9215 VerifyReferrerAfterRedirect(
9216 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409217 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549218
9219 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409220 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549221
estarkc8ccba82017-06-13 22:37:409222 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9223 referrer);
9224
9225 // The original referrer set on the request is expected to obey the referrer
9226 // policy and already be stripped to the origin; thus this test case just
9227 // checks that this policy doesn't cause the referrer to change when following
9228 // a redirect.
9229 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9230 referrer.GetOrigin());
9231
9232 VerifyReferrerAfterRedirect(
9233 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9234 referrer);
9235
9236 // The original referrer set on the request is expected to obey the referrer
9237 // policy and already be stripped to the origin; thus this test case just
9238 // checks that this policy doesn't cause the referrer to change when following
9239 // a redirect.
9240 VerifyReferrerAfterRedirect(
9241 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9242 referrer.GetOrigin(), referrer.GetOrigin());
9243
9244 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549245}
9246
tommycli59a63432015-11-06 00:10:559247TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
9248 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9249 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409250 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549251
9252 VerifyReferrerAfterRedirect(
9253 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409254 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549255
9256 VerifyReferrerAfterRedirect(
9257 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409258 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549259
9260 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409261 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
9262 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549263
estarkc8ccba82017-06-13 22:37:409264 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9265 referrer);
9266
9267 // The original referrer set on the request is expected to obey the referrer
9268 // policy and already be stripped to the origin; thus this test case just
9269 // checks that this policy doesn't cause the referrer to change when following
9270 // a redirect.
9271 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9272 referrer.GetOrigin());
9273
9274 VerifyReferrerAfterRedirect(
9275 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9276
9277 // The original referrer set on the request is expected to obey the referrer
9278 // policy and already be stripped to the origin; thus this test case just
9279 // checks that this policy doesn't cause the referrer to change when following
9280 // a redirect.
9281 VerifyReferrerAfterRedirect(
9282 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9283 referrer.GetOrigin(), referrer.GetOrigin());
9284
9285 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549286}
9287
9288TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:559289 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409290 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549291
9292 VerifyReferrerAfterRedirect(
9293 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409294 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549295
9296 VerifyReferrerAfterRedirect(
9297 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409298 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549299
9300 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409301 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549302
estarkc8ccba82017-06-13 22:37:409303 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9304 referrer);
9305
9306 // The original referrer set on the request is expected to obey the referrer
9307 // policy and already be stripped to the origin; thus this test case just
9308 // checks that this policy doesn't cause the referrer to change when following
9309 // a redirect.
9310 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9311 referrer.GetOrigin());
9312
9313 VerifyReferrerAfterRedirect(
9314 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9315 referrer);
9316
9317 // The original referrer set on the request is expected to obey the referrer
9318 // policy and already be stripped to the origin; thus this test case just
9319 // checks that this policy doesn't cause the referrer to change when following
9320 // a redirect.
9321 VerifyReferrerAfterRedirect(
9322 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9323 referrer.GetOrigin(), referrer.GetOrigin());
9324
9325 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549326}
9327
tommycli59a63432015-11-06 00:10:559328TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
9329 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9330 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409331 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549332
9333 VerifyReferrerAfterRedirect(
9334 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409335 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549336
9337 VerifyReferrerAfterRedirect(
9338 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409339 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549340
9341 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409342 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559343 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549344
estarkc8ccba82017-06-13 22:37:409345 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9346 referrer);
9347
9348 // The original referrer set on the request is expected to obey the referrer
9349 // policy and already be stripped to the origin; thus this test case just
9350 // checks that this policy doesn't cause the referrer to change when following
9351 // a redirect.
9352 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9353 referrer.GetOrigin());
9354
9355 VerifyReferrerAfterRedirect(
9356 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9357
9358 // The original referrer set on the request is expected to obey the referrer
9359 // policy and already be stripped to the origin; thus this test case just
9360 // checks that this policy doesn't cause the referrer to change when following
9361 // a redirect.
9362 VerifyReferrerAfterRedirect(
9363 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9364 referrer.GetOrigin(), referrer.GetOrigin());
9365
9366 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549367}
9368
tommycli59a63432015-11-06 00:10:559369TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
9370 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9371 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409372 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549373
9374 VerifyReferrerAfterRedirect(
9375 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409376 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549377
9378 VerifyReferrerAfterRedirect(
9379 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409380 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549381
9382 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409383 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559384 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549385
estarkc8ccba82017-06-13 22:37:409386 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9387 referrer);
9388
9389 // The original referrer set on the request is expected to obey the referrer
9390 // policy and already be stripped to the origin; thus this test case just
9391 // checks that this policy doesn't cause the referrer to change when following
9392 // a redirect.
9393 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9394 referrer.GetOrigin());
9395
9396 VerifyReferrerAfterRedirect(
9397 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9398
9399 // The original referrer set on the request is expected to obey the referrer
9400 // policy and already be stripped to the origin; thus this test case just
9401 // checks that this policy doesn't cause the referrer to change when following
9402 // a redirect.
9403 VerifyReferrerAfterRedirect(
9404 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9405 referrer.GetOrigin(), referrer.GetOrigin());
9406
9407 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549408}
9409
tommycli59a63432015-11-06 00:10:559410TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
9411 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9412 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409413 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549414
9415 VerifyReferrerAfterRedirect(
9416 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409417 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549418
9419 VerifyReferrerAfterRedirect(
9420 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409421 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549422
9423 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409424 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559425 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549426
estarkc8ccba82017-06-13 22:37:409427 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9428 referrer);
9429
9430 // The original referrer set on the request is expected to obey the referrer
9431 // policy and already be stripped to the origin; thus this test case just
9432 // checks that this policy doesn't cause the referrer to change when following
9433 // a redirect.
9434 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9435 referrer.GetOrigin());
9436
9437 VerifyReferrerAfterRedirect(
9438 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9439
9440 // The original referrer set on the request is expected to obey the referrer
9441 // policy and already be stripped to the origin, though it should be
9442 // subsequently cleared during the downgrading redirect.
9443 VerifyReferrerAfterRedirect(
9444 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9445 referrer.GetOrigin(), GURL());
9446
9447 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549448}
9449
[email protected]73e0bba2009-02-19 22:57:099450class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:509451 public:
fdorayf33fede2017-05-11 21:18:109452 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:099453 default_context_.set_network_delegate(&default_network_delegate_);
9454 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:509455 }
dcheng67be2b1f2014-10-27 21:47:299456 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:509457
9458 protected:
[email protected]ceefd7fd2012-11-29 00:36:249459 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:099460 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:469461};
9462
[email protected]c044616e2013-02-20 02:01:269463TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:559464 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9465 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229466 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119467 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:469468
[email protected]ea224582008-12-07 20:25:469469 TestDelegate d;
9470 {
danakj8522a25b2016-04-16 00:17:369471 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169472 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9473 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199474 r->Start();
9475 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:469476
[email protected]255620da2013-08-19 13:14:299477 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:469478
9479 EXPECT_EQ(1, d.response_started_count());
9480 EXPECT_FALSE(d.received_data_before_response());
9481 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199482 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:199483 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199484 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199485 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199486 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:469487 }
[email protected]ea224582008-12-07 20:25:469488}
9489
[email protected]5774ada2010-07-15 06:30:549490TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:559491 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9492 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9493 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229494 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119495 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339496
9497 bool err_allowed = true;
9498 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9499 TestDelegate d;
9500 {
9501 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369502 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169503 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9504 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339505
[email protected]f7022f32014-08-21 16:32:199506 r->Start();
9507 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339508
[email protected]255620da2013-08-19 13:14:299509 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:339510
9511 EXPECT_EQ(1, d.response_started_count());
9512 EXPECT_FALSE(d.received_data_before_response());
9513 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179514 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339515 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199516 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179517 } else {
[email protected]bacff652009-03-31 17:50:339518 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179519 }
[email protected]bacff652009-03-31 17:50:339520 }
9521 }
9522}
9523
[email protected]5774ada2010-07-15 06:30:549524TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:559525 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9526 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
9527 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229528 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119529 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339530
9531 // Iterate from false to true, just so that we do the opposite of the
9532 // previous test in order to increase test coverage.
9533 bool err_allowed = false;
9534 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9535 TestDelegate d;
9536 {
9537 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369538 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169539 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9540 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339541
[email protected]f7022f32014-08-21 16:32:199542 r->Start();
9543 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339544
[email protected]255620da2013-08-19 13:14:299545 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:339546
9547 EXPECT_EQ(1, d.response_started_count());
9548 EXPECT_FALSE(d.received_data_before_response());
9549 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179550 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339551 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199552 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179553 } else {
[email protected]bacff652009-03-31 17:50:339554 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179555 }
[email protected]bacff652009-03-31 17:50:339556 }
9557 }
9558}
[email protected]73e0bba2009-02-19 22:57:099559
tommycli59a63432015-11-06 00:10:559560// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
9561// security state. (see http://crbug.com/550977).
9562#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:449563// This tests that a load of www.google.com with a certificate error sets
9564// the |certificate_errors_are_fatal| flag correctly. This flag will cause
9565// the interstitial to be fatal.
9566TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
xunjieli815ad5b2017-07-18 15:51:359567#if !BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
9568 SetTransportSecurityStateSourceForTesting(&test0::kHSTSSource);
9569#endif
tommycli59a63432015-11-06 00:10:559570 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9571 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9572 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449573 ASSERT_TRUE(test_server.Start());
9574
9575 // We require that the URL be www.google.com in order to pick up the
9576 // preloaded HSTS entries in the TransportSecurityState. This means that we
9577 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:249578 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449579
9580 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249581 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449582 TestURLRequestContext context(true);
9583 context.set_network_delegate(&network_delegate);
9584 context.set_host_resolver(&host_resolver);
9585 TransportSecurityState transport_security_state;
9586 context.set_transport_security_state(&transport_security_state);
9587 context.Init();
9588
9589 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369590 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199591 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:369592 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169593 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449594
[email protected]f7022f32014-08-21 16:32:199595 r->Start();
9596 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449597
[email protected]255620da2013-08-19 13:14:299598 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449599
9600 EXPECT_EQ(1, d.response_started_count());
9601 EXPECT_FALSE(d.received_data_before_response());
9602 EXPECT_TRUE(d.have_certificate_errors());
9603 EXPECT_TRUE(d.certificate_errors_are_fatal());
9604}
9605
9606// This tests that cached HTTPS page loads do not cause any updates to the
9607// TransportSecurityState.
9608TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
xunjieli815ad5b2017-07-18 15:51:359609#if !BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
9610 SetTransportSecurityStateSourceForTesting(&test0::kHSTSSource);
9611#endif
[email protected]316c1e5e2012-09-12 15:17:449612 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
9613 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:559614 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9615 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9616 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449617 ASSERT_TRUE(test_server.Start());
9618
[email protected]9e6968d2014-05-07 21:46:269619 // We require that the URL be www.google.com in order to pick up the static
9620 // and dynamic STS and PKP entries in the TransportSecurityState. This means
9621 // that we have to use a MockHostResolver in order to direct www.google.com to
9622 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449623
9624 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249625 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449626 TestURLRequestContext context(true);
9627 context.set_network_delegate(&network_delegate);
9628 context.set_host_resolver(&host_resolver);
9629 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:269630
martijnc0d6b622015-06-30 19:14:409631 TransportSecurityState::STSState static_sts_state;
9632 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269633 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:409634 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:449635 context.set_transport_security_state(&transport_security_state);
9636 context.Init();
9637
martijnc0d6b622015-06-30 19:14:409638 TransportSecurityState::STSState dynamic_sts_state;
9639 TransportSecurityState::PKPState dynamic_pkp_state;
9640 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
9641 &dynamic_sts_state));
9642 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
9643 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269644
[email protected]316c1e5e2012-09-12 15:17:449645 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369646 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199647 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:369648 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169649 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449650
[email protected]f7022f32014-08-21 16:32:199651 r->Start();
9652 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449653
[email protected]255620da2013-08-19 13:14:299654 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449655
9656 EXPECT_EQ(1, d.response_started_count());
9657 EXPECT_FALSE(d.received_data_before_response());
9658 EXPECT_TRUE(d.have_certificate_errors());
9659 EXPECT_TRUE(d.certificate_errors_are_fatal());
9660
[email protected]9e6968d2014-05-07 21:46:269661 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:409662 TransportSecurityState::STSState new_static_sts_state;
9663 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269664 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:409665 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
9666 TransportSecurityState::STSState new_dynamic_sts_state;
9667 TransportSecurityState::PKPState new_dynamic_pkp_state;
9668 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
9669 "www.google.com", &new_dynamic_sts_state));
9670 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
9671 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269672
martijnc0d6b622015-06-30 19:14:409673 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
9674 EXPECT_EQ(new_static_sts_state.include_subdomains,
9675 static_sts_state.include_subdomains);
9676 EXPECT_EQ(new_static_pkp_state.include_subdomains,
9677 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:489678 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
9679 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
9680 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:449681}
9682
[email protected]8ccc69f2012-11-28 19:52:149683// Make sure HSTS preserves a POST request's method and body.
9684TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
9685 static const char kData[] = "hello world";
9686
tommycli59a63432015-11-06 00:10:559687 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9688 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229689 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:149690 ASSERT_TRUE(test_server.Start());
9691
9692
9693 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9694 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:559695 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:229696 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:149697 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:149698
9699 // Force https for www.somewhere.com.
9700 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:209701 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
9702 bool include_subdomains = false;
9703 transport_security_state.AddHSTS("www.somewhere.com", expiry,
9704 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:149705
9706 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9707
9708 TestURLRequestContext context(true);
9709 context.set_host_resolver(&host_resolver);
9710 context.set_transport_security_state(&transport_security_state);
9711 context.set_network_delegate(&network_delegate);
9712 context.Init();
9713
9714 TestDelegate d;
9715 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
9716 // cause a certificate error. Ignore the error.
9717 d.set_allow_certificate_errors(true);
9718
danakj8522a25b2016-04-16 00:17:369719 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199720 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:369721 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169722 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199723 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079724 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:149725
[email protected]f7022f32014-08-21 16:32:199726 req->Start();
[email protected]255620da2013-08-19 13:14:299727 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:149728
[email protected]f7022f32014-08-21 16:32:199729 EXPECT_EQ("https", req->url().scheme());
9730 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:149731 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:409732
9733 LoadTimingInfo load_timing_info;
9734 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
9735 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
9736 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:149737}
9738
rob4e0be1f2014-09-11 23:40:229739// Make sure that the CORS headers are added to cross-origin HSTS redirects.
9740TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
9741 static const char kOriginHeaderValue[] = "http://www.example.com";
9742
tommycli59a63432015-11-06 00:10:559743 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9744 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:229745 ASSERT_TRUE(test_server.Start());
9746
9747 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9748 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:559749 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
9750 // default.
rob4e0be1f2014-09-11 23:40:229751 MockHostResolver host_resolver;
9752
9753 TransportSecurityState transport_security_state;
9754 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
9755 bool include_subdomains = false;
9756 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
9757
9758 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9759
9760 MockCertVerifier cert_verifier;
9761 cert_verifier.set_default_result(OK);
9762
9763 TestURLRequestContext context(true);
9764 context.set_host_resolver(&host_resolver);
9765 context.set_transport_security_state(&transport_security_state);
9766 context.set_network_delegate(&network_delegate);
9767 context.set_cert_verifier(&cert_verifier);
9768 context.Init();
9769
9770 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
9771 test_server.host_port_pair().port()));
9772 url::Replacements<char> replacements;
9773 const char kNewScheme[] = "https";
9774 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
9775 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
9776
9777 TestDelegate d;
9778 // Quit on redirect to allow response header inspection upon redirect.
9779 d.set_quit_on_redirect(true);
9780
rhalavatib7bd7c792017-04-27 05:25:169781 std::unique_ptr<URLRequest> req(context.CreateRequest(
9782 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:229783 // Set Origin header to simulate a cross-origin request.
9784 HttpRequestHeaders request_headers;
9785 request_headers.SetHeader("Origin", kOriginHeaderValue);
9786 req->SetExtraRequestHeaders(request_headers);
9787
9788 req->Start();
9789 base::RunLoop().Run();
9790
9791 EXPECT_EQ(1, d.received_redirect_count());
9792
9793 const HttpResponseHeaders* headers = req->response_headers();
9794 std::string redirect_location;
9795 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
9796 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
9797
9798 std::string received_cors_header;
9799 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
9800 &received_cors_header));
9801 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
9802}
9803
[email protected]316c1e5e2012-09-12 15:17:449804namespace {
9805
9806class SSLClientAuthTestDelegate : public TestDelegate {
9807 public:
9808 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
9809 }
dchengb03027d2014-10-21 12:00:209810 void OnCertificateRequested(URLRequest* request,
9811 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:449812 on_certificate_requested_count_++;
Gabriel Charette53a9ef812017-07-26 12:36:239813 base::RunLoop::QuitCurrentWhenIdleDeprecated();
[email protected]316c1e5e2012-09-12 15:17:449814 }
9815 int on_certificate_requested_count() {
9816 return on_certificate_requested_count_;
9817 }
9818 private:
9819 int on_certificate_requested_count_;
9820};
9821
9822} // namespace
9823
9824// TODO(davidben): Test the rest of the code. Specifically,
9825// - Filtering which certificates to select.
9826// - Sending a certificate back.
9827// - Getting a certificate request in an SSL renegotiation sending the
9828// HTTP request.
9829TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:559830 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9831 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:129832 ssl_config.client_cert_type =
9833 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
tommycli59a63432015-11-06 00:10:559834 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
9835 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229836 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449837 ASSERT_TRUE(test_server.Start());
9838
9839 SSLClientAuthTestDelegate d;
9840 {
danakj8522a25b2016-04-16 00:17:369841 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169842 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9843 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449844
[email protected]f7022f32014-08-21 16:32:199845 r->Start();
9846 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449847
[email protected]255620da2013-08-19 13:14:299848 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449849
9850 EXPECT_EQ(1, d.on_certificate_requested_count());
9851 EXPECT_FALSE(d.received_data_before_response());
9852 EXPECT_EQ(0, d.bytes_received());
9853
9854 // Send no certificate.
9855 // TODO(davidben): Get temporary client cert import (with keys) working on
9856 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:549857 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:449858
[email protected]255620da2013-08-19 13:14:299859 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449860
9861 EXPECT_EQ(1, d.response_started_count());
9862 EXPECT_FALSE(d.received_data_before_response());
9863 EXPECT_NE(0, d.bytes_received());
9864 }
9865}
9866
9867TEST_F(HTTPSRequestTest, ResumeTest) {
9868 // Test that we attempt a session resume when making two connections to the
9869 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:229870 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:449871 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:229872 SpawnedTestServer test_server(
9873 SpawnedTestServer::TYPE_HTTPS,
9874 ssl_options,
9875 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449876 ASSERT_TRUE(test_server.Start());
9877
9878 SSLClientSocket::ClearSessionCache();
9879
9880 {
9881 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369882 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169883 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
9884 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449885
[email protected]f7022f32014-08-21 16:32:199886 r->Start();
9887 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449888
[email protected]255620da2013-08-19 13:14:299889 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449890
9891 EXPECT_EQ(1, d.response_started_count());
9892 }
9893
9894 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
9895 CloseAllConnections();
9896
9897 {
9898 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369899 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169900 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
9901 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449902
[email protected]f7022f32014-08-21 16:32:199903 r->Start();
9904 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449905
[email protected]255620da2013-08-19 13:14:299906 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449907
9908 // The response will look like;
9909 // insert abc
9910 // lookup abc
9911 // insert xyz
9912 //
9913 // With a newline at the end which makes the split think that there are
9914 // four lines.
9915
9916 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:299917 std::vector<std::string> lines = base::SplitString(
9918 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:449919 ASSERT_EQ(4u, lines.size()) << d.data_received();
9920
9921 std::string session_id;
9922
9923 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:299924 std::vector<std::string> parts = base::SplitString(
9925 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:449926 ASSERT_EQ(2u, parts.size());
9927 if (i == 0) {
9928 EXPECT_EQ("insert", parts[0]);
9929 session_id = parts[1];
9930 } else {
9931 EXPECT_EQ("lookup", parts[0]);
9932 EXPECT_EQ(session_id, parts[1]);
9933 }
9934 }
9935 }
9936}
9937
Adam Langley32352ad2014-10-14 22:31:009938// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
9939// the result of fetching "ssl-session-cache" from the test server, indicates
9940// that exactly two different sessions were inserted, with no lookups etc.
9941static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:299942 std::vector<std::string> lines = base::SplitString(
9943 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:009944 ASSERT_EQ(3u, lines.size()) << session_info;
9945
9946 std::string session_id;
9947 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:299948 std::vector<std::string> parts = base::SplitString(
9949 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:009950 ASSERT_EQ(2u, parts.size());
9951 EXPECT_EQ("insert", parts[0]);
9952 if (i == 0) {
9953 session_id = parts[1];
9954 } else {
9955 EXPECT_NE(session_id, parts[1]);
9956 }
9957 }
9958}
9959
[email protected]316c1e5e2012-09-12 15:17:449960TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
9961 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
9962 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:229963 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:449964 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:229965 SpawnedTestServer test_server(
9966 SpawnedTestServer::TYPE_HTTPS,
9967 ssl_options,
9968 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449969 ASSERT_TRUE(test_server.Start());
9970
9971 SSLClientSocket::ClearSessionCache();
9972
9973 {
9974 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369975 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169976 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
9977 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449978
[email protected]f7022f32014-08-21 16:32:199979 r->Start();
9980 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449981
[email protected]255620da2013-08-19 13:14:299982 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449983
9984 EXPECT_EQ(1, d.response_started_count());
9985 }
9986
9987 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:419988 HttpNetworkSession::Context session_context;
9989 session_context.host_resolver = default_context_.host_resolver();
9990 session_context.cert_verifier = default_context_.cert_verifier();
9991 session_context.transport_security_state =
9992 default_context_.transport_security_state();
9993 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:209994 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:419995 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
9996 session_context.proxy_service = default_context_.proxy_service();
9997 session_context.ssl_config_service = default_context_.ssl_config_service();
9998 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:449999 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4110000 session_context.http_server_properties =
10001 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4410002
mmenke6ddfbea2017-05-31 21:48:4110003 HttpNetworkSession network_session(HttpNetworkSession::Params(),
10004 session_context);
zhongyi4928bd52017-02-08 02:16:2710005 std::unique_ptr<HttpCache> cache(
10006 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
10007 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4410008
10009 default_context_.set_http_transaction_factory(cache.get());
10010
10011 {
10012 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610013 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610014 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10015 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410016
[email protected]f7022f32014-08-21 16:32:1910017 r->Start();
10018 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410019
[email protected]255620da2013-08-19 13:14:2910020 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410021
10022 // The response will look like;
10023 // insert abc
10024 // insert xyz
10025 //
10026 // With a newline at the end which makes the split think that there are
10027 // three lines.
10028
10029 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010030 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:4410031 }
10032}
10033
[email protected]48d2b7c52014-06-27 01:16:5510034class HTTPSFallbackTest : public testing::Test {
10035 public:
fdorayf33fede2017-05-11 21:18:1010036 HTTPSFallbackTest() : context_(true) {
davidben095ebb52017-04-12 22:23:3410037 ssl_config_service_ = new TestSSLConfigService(
10038 true /* check for EV */, false /* online revocation checking */,
10039 false /* require rev. checking for local anchors */,
10040 false /* token binding enabled */);
10041 context_.set_ssl_config_service(ssl_config_service_.get());
10042 }
dcheng67be2b1f2014-10-27 21:47:2910043 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:5510044
10045 protected:
davidben095ebb52017-04-12 22:23:3410046 TestSSLConfigService* ssl_config_service() {
10047 return ssl_config_service_.get();
10048 }
10049
[email protected]48d2b7c52014-06-27 01:16:5510050 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
10051 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0010052 context_.Init();
10053 delegate_.set_allow_certificate_errors(true);
10054
[email protected]48d2b7c52014-06-27 01:16:5510055 SpawnedTestServer test_server(
10056 SpawnedTestServer::TYPE_HTTPS,
10057 ssl_options,
10058 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10059 ASSERT_TRUE(test_server.Start());
10060
tommycli59a63432015-11-06 00:10:5510061 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1610062 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5510063 request_->Start();
10064
10065 base::RunLoop().Run();
10066 }
10067
davidben095ebb52017-04-12 22:23:3410068 void ExpectConnection(int version) {
10069 EXPECT_EQ(1, delegate_.response_started_count());
10070 EXPECT_NE(0, delegate_.bytes_received());
10071 EXPECT_EQ(version, SSLConnectionStatusToVersion(
10072 request_->ssl_info().connection_status));
10073 }
10074
[email protected]48d2b7c52014-06-27 01:16:5510075 void ExpectFailure(int error) {
10076 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5010077 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5510078 }
10079
10080 private:
10081 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4710082 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610083 std::unique_ptr<URLRequest> request_;
davidben095ebb52017-04-12 22:23:3410084 scoped_refptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5510085};
10086
davidbenb127ca82015-06-15 19:05:4210087// Tests the TLS 1.0 fallback doesn't happen.
10088TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5510089 SpawnedTestServer::SSLOptions ssl_options(
10090 SpawnedTestServer::SSLOptions::CERT_OK);
10091 ssl_options.tls_intolerant =
10092 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
10093
10094 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5510095 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4210096}
10097
davidben5a312152016-06-27 22:11:4710098// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5510099TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4210100 SpawnedTestServer::SSLOptions ssl_options(
10101 SpawnedTestServer::SSLOptions::CERT_OK);
10102 ssl_options.tls_intolerant =
10103 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
10104
10105 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5510106 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
10107}
10108
davidben095ebb52017-04-12 22:23:3410109// Tests that TLS 1.3 interference results in a dedicated error code.
10110TEST_F(HTTPSFallbackTest, TLSv1_3Interference) {
10111 SpawnedTestServer::SSLOptions ssl_options(
10112 SpawnedTestServer::SSLOptions::CERT_OK);
10113 ssl_options.tls_intolerant =
10114 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10115 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
10116
10117 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10118 ExpectFailure(ERR_SSL_VERSION_INTERFERENCE);
10119}
10120
10121// Tests that disabling TLS 1.3 leaves TLS 1.3 interference unnoticed.
10122TEST_F(HTTPSFallbackTest, TLSv1_3InterferenceDisableVersion) {
10123 SpawnedTestServer::SSLOptions ssl_options(
10124 SpawnedTestServer::SSLOptions::CERT_OK);
10125 ssl_options.tls_intolerant =
10126 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10127 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_2);
10128
10129 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10130 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_2);
10131}
10132
[email protected]a8fed1742013-12-27 02:14:2410133class HTTPSSessionTest : public testing::Test {
10134 public:
fdorayf33fede2017-05-11 21:18:1010135 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5910136 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410137
10138 default_context_.set_network_delegate(&default_network_delegate_);
10139 default_context_.set_cert_verifier(&cert_verifier_);
10140 default_context_.Init();
10141 }
dcheng67be2b1f2014-10-27 21:47:2910142 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:2410143
10144 protected:
10145 MockCertVerifier cert_verifier_;
10146 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
10147 TestURLRequestContext default_context_;
10148};
10149
10150// Tests that session resumption is not attempted if an invalid certificate
10151// is presented.
10152TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
10153 SpawnedTestServer::SSLOptions ssl_options;
10154 ssl_options.record_resume = true;
10155 SpawnedTestServer test_server(
10156 SpawnedTestServer::TYPE_HTTPS,
10157 ssl_options,
10158 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10159 ASSERT_TRUE(test_server.Start());
10160
10161 SSLClientSocket::ClearSessionCache();
10162
10163 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5910164 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2410165 {
10166 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610167 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610168 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10169 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410170
[email protected]f7022f32014-08-21 16:32:1910171 r->Start();
10172 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410173
10174 base::RunLoop().Run();
10175
10176 EXPECT_EQ(1, d.response_started_count());
10177 }
10178
10179 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10180 CloseAllConnections();
10181
10182 // Now change the certificate to be acceptable (so that the response is
10183 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5910184 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410185 {
10186 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610187 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610188 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10189 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410190
[email protected]f7022f32014-08-21 16:32:1910191 r->Start();
10192 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410193
10194 base::RunLoop().Run();
10195
10196 // The response will look like;
10197 // insert abc
10198 // insert xyz
10199 //
10200 // With a newline at the end which makes the split think that there are
10201 // three lines.
10202 //
10203 // If a session was presented (eg: a bug), then the response would look
10204 // like;
10205 // insert abc
10206 // lookup abc
10207 // insert xyz
10208
10209 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010210 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:2410211 }
10212}
10213
[email protected]dffe8242012-03-20 15:14:2710214// This the fingerprint of the "Testing CA" certificate used by the testserver.
10215// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5810216static const SHA256HashValue kOCSPTestCertFingerprint = {{
10217 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
10218 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
10219 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1510220}};
[email protected]dffe8242012-03-20 15:14:2710221
[email protected]51523f52013-07-31 21:57:2810222// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
10223// testserver.
mattm0b12a6f2016-11-29 19:57:1610224static const SHA256HashValue kOCSPTestCertSPKI = {{
10225 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
10226 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
10227 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
10228}};
[email protected]51523f52013-07-31 21:57:2810229
[email protected]dffe8242012-03-20 15:14:2710230// This is the policy OID contained in the certificates that testserver
10231// generates.
10232static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
10233
10234class HTTPSOCSPTest : public HTTPSRequestTest {
10235 public:
10236 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0910237 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0810238 ev_test_policy_(
10239 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
10240 kOCSPTestCertFingerprint,
10241 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0210242 }
10243
dcheng67be2b1f2014-10-27 21:47:2910244 void SetUp() override {
rsleevid6de8302016-06-21 01:33:2010245 context_.SetCTPolicyEnforcer(
Jeremy Roman0579ed62017-08-29 15:56:1910246 std::make_unique<AllowAnyCertCTPolicyEnforcer>());
rsleevid6de8302016-06-21 01:33:2010247 SetupContext();
[email protected]ef2bf422012-05-11 03:27:0910248 context_.Init();
[email protected]dffe8242012-03-20 15:14:2710249
[email protected]cba24642014-08-15 20:49:5910250 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2010251 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:4210252 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:5010253 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2710254
svaldez2135be52016-04-20 16:34:5310255#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0910256 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2710257 EnsureNSSHttpIOInit();
10258#endif
10259 }
10260
dadrian612337a2016-07-20 22:36:5810261 void DoConnectionWithDelegate(
10262 const SpawnedTestServer::SSLOptions& ssl_options,
10263 TestDelegate* delegate,
10264 SSLInfo* out_ssl_info) {
10265 // Always overwrite |out_ssl_info|.
10266 out_ssl_info->Reset();
10267
[email protected]ce7d0cbc2013-05-03 18:57:2210268 SpawnedTestServer test_server(
10269 SpawnedTestServer::TYPE_HTTPS,
10270 ssl_options,
10271 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2710272 ASSERT_TRUE(test_server.Start());
10273
dadrian612337a2016-07-20 22:36:5810274 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1610275 std::unique_ptr<URLRequest> r(
10276 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
10277 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910278 r->Start();
[email protected]dffe8242012-03-20 15:14:2710279
[email protected]255620da2013-08-19 13:14:2910280 base::RunLoop().Run();
dadrian612337a2016-07-20 22:36:5810281 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2710282
dadrian612337a2016-07-20 22:36:5810283 *out_ssl_info = r->ssl_info();
10284 }
10285
10286 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
10287 CertStatus* out_cert_status) {
10288 // Always overwrite |out_cert_status|.
10289 *out_cert_status = 0;
10290
10291 TestDelegate d;
10292 SSLInfo ssl_info;
10293 ASSERT_NO_FATAL_FAILURE(
10294 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
10295
10296 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2710297 }
10298
dcheng67be2b1f2014-10-27 21:47:2910299 ~HTTPSOCSPTest() override {
svaldez2135be52016-04-20 16:34:5310300#if defined(USE_NSS_CERTS)
[email protected]dffe8242012-03-20 15:14:2710301 ShutdownNSSHttpIO();
10302#endif
10303 }
10304
[email protected]a13234c2012-03-20 21:45:0210305 protected:
rsleevid6de8302016-06-21 01:33:2010306 class AllowAnyCertCTPolicyEnforcer : public CTPolicyEnforcer {
10307 public:
10308 AllowAnyCertCTPolicyEnforcer() = default;
10309 ~AllowAnyCertCTPolicyEnforcer() override = default;
10310
10311 ct::CertPolicyCompliance DoesConformToCertPolicy(
10312 X509Certificate* cert,
10313 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:2010314 const NetLogWithSource& net_log) override {
rsleevid6de8302016-06-21 01:33:2010315 return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS;
10316 }
rsleevid6de8302016-06-21 01:33:2010317 };
[email protected]a13234c2012-03-20 21:45:0210318 // SetupContext configures the URLRequestContext that will be used for making
10319 // connetions to testserver. This can be overridden in test subclasses for
10320 // different behaviour.
rsleevid6de8302016-06-21 01:33:2010321 virtual void SetupContext() {
10322 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1410323 true /* check for EV */, true /* online revocation checking */,
10324 false /* require rev. checking for local
10325 anchors */,
10326 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0210327 }
10328
danakj8522a25b2016-04-16 00:17:3610329 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:0910330 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610331 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2710332};
10333
[email protected]a13234c2012-03-20 21:45:0210334static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2010335#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0210336 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
10337 // have that ability on other platforms.
10338 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
10339#else
10340 return 0;
10341#endif
10342}
10343
[email protected]3a86a712013-07-30 07:16:2010344// SystemSupportsHardFailRevocationChecking returns true iff the current
10345// operating system supports revocation checking and can distinguish between
10346// situations where a given certificate lacks any revocation information (eg:
10347// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
10348// revocation information cannot be obtained (eg: the CRL was unreachable).
10349// If it does not, then tests which rely on 'hard fail' behaviour should be
10350// skipped.
10351static bool SystemSupportsHardFailRevocationChecking() {
svaldez2135be52016-04-20 16:34:5310352#if defined(OS_WIN) || defined(USE_NSS_CERTS)
[email protected]3a86a712013-07-30 07:16:2010353 return true;
10354#else
10355 return false;
10356#endif
10357}
10358
[email protected]a13234c2012-03-20 21:45:0210359// SystemUsesChromiumEVMetadata returns true iff the current operating system
10360// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
10361// several tests are effected because our testing EV certificate won't be
10362// recognised as EV.
10363static bool SystemUsesChromiumEVMetadata() {
davidben965721b2017-05-03 19:40:3110364#if defined(OS_ANDROID)
mattm1a282f52016-11-10 21:49:4210365 // On Android, we use the system to tell us whether a certificate is EV or not
10366 // and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:0110367 return false;
10368#else
10369 return true;
10370#endif
10371}
10372
mattmaf868e72016-09-23 23:25:2010373// Returns the expected CertStatus for tests that expect an online revocation
10374// check failure as a result of checking a test EV cert, which will not
10375// actually trigger an online revocation check on some platforms.
10376static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
10377 if (SystemUsesChromiumEVMetadata()) {
10378 return ExpectedCertStatusForFailedOnlineRevocationCheck();
10379 } else {
10380 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
10381 // be enabled, and thus there will not be a revocation check to fail.
10382 return 0u;
10383 }
10384}
10385
[email protected]b6f2de32012-08-17 04:35:0810386static bool SystemSupportsOCSP() {
davidben7ee23542016-06-03 18:27:3310387#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0210388 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
10389 return false;
10390#else
10391 return true;
10392#endif
10393}
10394
davidbend1fb2f12014-11-08 02:51:0010395static bool SystemSupportsOCSPStapling() {
davidben7ee23542016-06-03 18:27:3310396#if defined(USE_NSS_CERTS) || defined(OS_WIN)
mathpc992e602015-10-21 20:34:0310397 return true;
mathpc992e602015-10-21 20:34:0310398#else
10399 return false;
10400#endif
davidbend1fb2f12014-11-08 02:51:0010401}
10402
[email protected]dffe8242012-03-20 15:14:2710403TEST_F(HTTPSOCSPTest, Valid) {
10404 if (!SystemSupportsOCSP()) {
10405 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10406 return;
10407 }
10408
[email protected]ce7d0cbc2013-05-03 18:57:2210409 SpawnedTestServer::SSLOptions ssl_options(
10410 SpawnedTestServer::SSLOptions::CERT_AUTO);
10411 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2710412
[email protected]924e9f92012-12-16 22:00:5310413 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210414 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710415
10416 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10417
[email protected]a13234c2012-03-20 21:45:0210418 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10419 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2710420
10421 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10422}
10423
10424TEST_F(HTTPSOCSPTest, Revoked) {
10425 if (!SystemSupportsOCSP()) {
10426 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10427 return;
10428 }
10429
[email protected]ce7d0cbc2013-05-03 18:57:2210430 SpawnedTestServer::SSLOptions ssl_options(
10431 SpawnedTestServer::SSLOptions::CERT_AUTO);
10432 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2710433
10434 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210435 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710436
[email protected]dffe8242012-03-20 15:14:2710437 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2710438 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10439 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10440}
10441
10442TEST_F(HTTPSOCSPTest, Invalid) {
10443 if (!SystemSupportsOCSP()) {
10444 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10445 return;
10446 }
10447
[email protected]ce7d0cbc2013-05-03 18:57:2210448 SpawnedTestServer::SSLOptions ssl_options(
10449 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810450 ssl_options.ocsp_status =
10451 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2710452
[email protected]924e9f92012-12-16 22:00:5310453 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210454 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710455
[email protected]a13234c2012-03-20 21:45:0210456 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2710457 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2710458
10459 // Without a positive OCSP response, we shouldn't show the EV status.
10460 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10461 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10462}
[email protected]a13234c2012-03-20 21:45:0210463
davidbend1fb2f12014-11-08 02:51:0010464TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0310465 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0010466 LOG(WARNING)
10467 << "Skipping test because system doesn't support OCSP stapling";
10468 return;
10469 }
10470
10471 SpawnedTestServer::SSLOptions ssl_options(
10472 SpawnedTestServer::SSLOptions::CERT_AUTO);
10473 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10474 ssl_options.staple_ocsp_response = true;
10475 ssl_options.ocsp_server_unavailable = true;
10476
10477 CertStatus cert_status;
10478 DoConnection(ssl_options, &cert_status);
10479
10480 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10481
10482 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10483 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10484
10485 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10486}
10487
davidben6c3191b2014-11-21 22:38:0410488// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4810489#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0410490#define MAYBE_RevokedStapled DISABLED_RevokedStapled
10491#else
10492#define MAYBE_RevokedStapled RevokedStapled
10493#endif
10494TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0310495 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0010496 LOG(WARNING)
10497 << "Skipping test because system doesn't support OCSP stapling";
10498 return;
10499 }
10500
10501 SpawnedTestServer::SSLOptions ssl_options(
10502 SpawnedTestServer::SSLOptions::CERT_AUTO);
10503 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
10504 ssl_options.staple_ocsp_response = true;
10505 ssl_options.ocsp_server_unavailable = true;
10506
10507 CertStatus cert_status;
10508 DoConnection(ssl_options, &cert_status);
10509
10510 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10511 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10512 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10513}
10514
dadriand476e652016-07-26 21:33:2410515TEST_F(HTTPSOCSPTest, ExpectStapleReportSentOnMissing) {
xunjieli815ad5b2017-07-18 15:51:3510516#if !BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
10517 SetTransportSecurityStateSourceForTesting(&test0::kHSTSSource);
10518#endif
dadriand476e652016-07-26 21:33:2410519 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10520 https_test_server.SetSSLConfig(
10521 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10522 https_test_server.ServeFilesFromSourceDirectory(
10523 base::FilePath(kTestFilePath));
10524 ASSERT_TRUE(https_test_server.Start());
10525
10526 // Set up a MockCertVerifier to accept the certificate that the server sends,
10527 // but not provide any OCSP information.
10528 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10529 ASSERT_TRUE(cert);
10530 MockCertVerifier cert_verifier;
10531 CertVerifyResult verify_result;
10532 verify_result.verified_cert = cert;
10533 verify_result.is_issued_by_known_root = true;
10534 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
10535 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
10536
10537 // Catch the Expect-Staple report.
10538 TransportSecurityState transport_security_state;
10539 MockCertificateReportSender mock_report_sender;
10540 transport_security_state.SetReportSender(&mock_report_sender);
10541
10542 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
10543 // that the request can be sent to a site on the Expect-Staple preload list.
10544 MockHostResolver host_resolver;
10545 TestNetworkDelegate network_delegate;
10546 TestURLRequestContext context(true);
10547 context.set_host_resolver(&host_resolver);
10548 context.set_transport_security_state(&transport_security_state);
10549 context.set_network_delegate(&network_delegate);
10550 context.set_cert_verifier(&cert_verifier);
10551 context.Init();
10552
10553 // Now send a request to trigger the violation.
10554 TestDelegate d;
10555 GURL url = https_test_server.GetURL("/");
10556 GURL::Replacements replace_host;
10557 replace_host.SetHostStr(kExpectStapleStaticHostname);
10558 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610559 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
10560 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2410561 violating_request->Start();
10562 base::RunLoop().Run();
10563
10564 // Confirm a report was sent.
10565 EXPECT_FALSE(mock_report_sender.latest_report().empty());
10566 EXPECT_EQ(GURL(kExpectStapleReportURI),
10567 mock_report_sender.latest_report_uri());
10568}
10569
estark13e0b312016-12-22 23:52:3210570// Tests that Expect-Staple reports are not sent for connections on which there
10571// is a certificate error.
10572TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnMissingWithCertError) {
10573 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10574 https_test_server.SetSSLConfig(
10575 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10576 https_test_server.ServeFilesFromSourceDirectory(
10577 base::FilePath(kTestFilePath));
10578 ASSERT_TRUE(https_test_server.Start());
10579
10580 // Set up a MockCertVerifier to report an error for the certificate
10581 // and indicate that there was no stapled OCSP response.
10582 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10583 ASSERT_TRUE(cert);
10584 MockCertVerifier cert_verifier;
10585 CertVerifyResult verify_result;
10586 verify_result.cert_status = CERT_STATUS_DATE_INVALID;
10587 verify_result.verified_cert = cert;
10588 verify_result.is_issued_by_known_root = true;
10589 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
10590 cert_verifier.AddResultForCert(cert.get(), verify_result,
10591 ERR_CERT_DATE_INVALID);
10592
10593 // Set up a mock report sender so that the test can check that an
10594 // Expect-Staple report is not sent.
10595 TransportSecurityState transport_security_state;
10596 MockCertificateReportSender mock_report_sender;
10597 transport_security_state.SetReportSender(&mock_report_sender);
10598
10599 TestNetworkDelegate network_delegate;
10600 TestURLRequestContext context(true);
10601
10602 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
10603 MockHostResolver host_resolver;
10604 context.set_host_resolver(&host_resolver);
10605
10606 context.set_transport_security_state(&transport_security_state);
10607 context.set_network_delegate(&network_delegate);
10608 context.set_cert_verifier(&cert_verifier);
10609 context.Init();
10610
10611 // Make a connection to |kExpectStapleStaticHostname|. Because the
10612 // |verify_result| used with the |cert_verifier| will indicate a certificate
10613 // error, an Expect-Staple report should not be sent.
10614 TestDelegate d;
10615 GURL url = https_test_server.GetURL("/");
10616 GURL::Replacements replace_host;
10617 replace_host.SetHostStr(kExpectStapleStaticHostname);
10618 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610619 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
10620 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3210621 violating_request->Start();
10622 base::RunLoop().Run();
10623
10624 // Confirm a report was not sent.
10625 EXPECT_TRUE(mock_report_sender.latest_report().empty());
10626 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
10627}
10628
dadriand476e652016-07-26 21:33:2410629TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnValid) {
10630 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10631 https_test_server.SetSSLConfig(
10632 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10633 https_test_server.ServeFilesFromSourceDirectory(
10634 base::FilePath(kTestFilePath));
10635 ASSERT_TRUE(https_test_server.Start());
10636
10637 // Set up a MockCertVerifier to accept the certificate that the server sends,
10638 // and provide GOOD revocation status.
10639 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10640 ASSERT_TRUE(cert);
10641 MockCertVerifier cert_verifier;
10642 CertVerifyResult verify_result;
10643 verify_result.verified_cert = cert;
10644 verify_result.is_issued_by_known_root = true;
10645 verify_result.ocsp_result.response_status = OCSPVerifyResult::PROVIDED;
10646 verify_result.ocsp_result.revocation_status = OCSPRevocationStatus::GOOD;
10647 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
10648
10649 // Catch the Expect-Staple report.
10650 TransportSecurityState transport_security_state;
10651 MockCertificateReportSender mock_report_sender;
10652 transport_security_state.SetReportSender(&mock_report_sender);
10653
10654 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
10655 // that the request can be sent to a site on the Expect-Staple preload list.
10656 MockHostResolver host_resolver;
10657 TestNetworkDelegate network_delegate;
10658 TestURLRequestContext context(true);
10659 context.set_host_resolver(&host_resolver);
10660 context.set_transport_security_state(&transport_security_state);
10661 context.set_network_delegate(&network_delegate);
10662 context.set_cert_verifier(&cert_verifier);
10663 context.Init();
10664
10665 // This request should not not trigger an Expect-Staple violation.
10666 TestDelegate d;
10667 GURL url = https_test_server.GetURL("/");
10668 GURL::Replacements replace_host;
10669 replace_host.SetHostStr(kExpectStapleStaticHostname);
10670 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610671 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
10672 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2410673 ok_request->Start();
10674 base::RunLoop().Run();
10675
10676 // Check that no report was sent.
10677 EXPECT_TRUE(mock_report_sender.latest_report().empty());
10678 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
10679}
10680
estark13e0b312016-12-22 23:52:3210681// Tests that an Expect-Staple report is not sent when OCSP details are not
10682// checked on the connection.
10683TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnNotChecked) {
10684 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10685 https_test_server.SetSSLConfig(
10686 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10687 https_test_server.ServeFilesFromSourceDirectory(
10688 base::FilePath(kTestFilePath));
10689 ASSERT_TRUE(https_test_server.Start());
10690
10691 // Set up a MockCertVerifier to accept the certificate that the server sends,
10692 // and set |ocsp_result| to indicate that OCSP stapling details were not
10693 // checked on the connection.
10694 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10695 ASSERT_TRUE(cert);
10696 MockCertVerifier cert_verifier;
10697 CertVerifyResult verify_result;
10698 verify_result.verified_cert = cert;
10699 verify_result.is_issued_by_known_root = true;
10700 verify_result.ocsp_result.response_status = OCSPVerifyResult::NOT_CHECKED;
10701 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
10702
10703 // Set up a mock report sender so that the test can check that an
10704 // Expect-Staple report is not sent.
10705 TransportSecurityState transport_security_state;
10706 MockCertificateReportSender mock_report_sender;
10707 transport_security_state.SetReportSender(&mock_report_sender);
10708
10709 TestNetworkDelegate network_delegate;
10710 TestURLRequestContext context(true);
10711
10712 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
10713 MockHostResolver host_resolver;
10714 context.set_host_resolver(&host_resolver);
10715
10716 context.set_transport_security_state(&transport_security_state);
10717 context.set_network_delegate(&network_delegate);
10718 context.set_cert_verifier(&cert_verifier);
10719 context.Init();
10720
10721 // Make a connection to |kExpectStapleStaticHostname|. Because the
10722 // |verify_result| used with the |cert_verifier| will indicate that OCSP
10723 // stapling details were not checked on the connection, an Expect-Staple
10724 // report should not be sent.
10725 TestDelegate d;
10726 GURL url = https_test_server.GetURL("/");
10727 GURL::Replacements replace_host;
10728 replace_host.SetHostStr(kExpectStapleStaticHostname);
10729 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610730 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
10731 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3210732 ok_request->Start();
10733 base::RunLoop().Run();
10734
10735 // Check that no report was sent.
10736 EXPECT_TRUE(mock_report_sender.latest_report().empty());
10737 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
10738}
10739
dadrian612337a2016-07-20 22:36:5810740static const struct OCSPVerifyTestData {
10741 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
10742 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
10743 OCSPVerifyResult::ResponseStatus response_status;
10744 bool has_revocation_status;
10745 OCSPRevocationStatus cert_status;
10746} kOCSPVerifyData[] = {
10747
10748 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10749 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10750 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10751 OCSPVerifyResult::PROVIDED,
10752 true,
10753 OCSPRevocationStatus::GOOD},
10754
10755 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10756 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10757 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10758 OCSPVerifyResult::INVALID_DATE,
10759 false,
10760 OCSPRevocationStatus::UNKNOWN},
10761
10762 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10763 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10764 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10765 OCSPVerifyResult::INVALID_DATE,
10766 false,
10767 OCSPRevocationStatus::UNKNOWN},
10768
10769 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10770 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10771 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10772 OCSPVerifyResult::INVALID_DATE,
10773 false,
10774 OCSPRevocationStatus::UNKNOWN},
10775
10776 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10777 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10778 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10779 OCSPVerifyResult::INVALID_DATE,
10780 false,
10781 OCSPRevocationStatus::UNKNOWN},
10782
10783 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
10784 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10785 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10786 OCSPVerifyResult::ERROR_RESPONSE,
10787 false,
10788 OCSPRevocationStatus::UNKNOWN},
10789
10790 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
10791 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10792 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10793 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
10794 false,
10795 OCSPRevocationStatus::UNKNOWN},
10796
10797 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
10798 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10799 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10800 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
10801 false,
10802 OCSPRevocationStatus::UNKNOWN},
10803
10804 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10805 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10806 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10807 OCSPVerifyResult::INVALID_DATE,
10808 false,
10809 OCSPRevocationStatus::UNKNOWN},
10810
10811 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10812 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10813 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10814 OCSPVerifyResult::PROVIDED,
10815 true,
10816 OCSPRevocationStatus::UNKNOWN},
10817
10818 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10819 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10820 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10821 OCSPVerifyResult::INVALID_DATE,
10822 false,
10823 OCSPRevocationStatus::UNKNOWN},
10824
10825 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10826 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10827 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10828 OCSPVerifyResult::INVALID_DATE,
10829 false,
10830 OCSPRevocationStatus::UNKNOWN},
10831
10832 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10833 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10834 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
10835 OCSPVerifyResult::BAD_PRODUCED_AT,
10836 false,
10837 OCSPRevocationStatus::UNKNOWN},
10838
10839 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10840 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10841 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
10842 OCSPVerifyResult::BAD_PRODUCED_AT,
10843 false,
10844 OCSPRevocationStatus::UNKNOWN},
10845
10846 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10847 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10848 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
10849 OCSPVerifyResult::BAD_PRODUCED_AT,
10850 false,
10851 OCSPRevocationStatus::UNKNOWN},
10852
10853 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10854 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10855 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10856 OCSPVerifyResult::PROVIDED,
10857 true,
10858 OCSPRevocationStatus::REVOKED},
10859
10860 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10861 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10862 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10863 OCSPVerifyResult::INVALID_DATE,
10864 false,
10865 OCSPRevocationStatus::UNKNOWN},
10866
10867 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10868 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10869 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10870 OCSPVerifyResult::INVALID_DATE,
10871 false,
10872 OCSPRevocationStatus::UNKNOWN},
10873
10874 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10875 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10876 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10877 OCSPVerifyResult::PROVIDED,
10878 true,
10879 OCSPRevocationStatus::GOOD},
10880
10881 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10882 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
10883 {SpawnedTestServer::SSLOptions::OCSP_OK,
10884 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10885 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10886 OCSPVerifyResult::PROVIDED,
10887 true,
10888 OCSPRevocationStatus::GOOD},
10889
10890 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10891 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
10892 {SpawnedTestServer::SSLOptions::OCSP_OK,
10893 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10894 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10895 OCSPVerifyResult::PROVIDED,
10896 true,
10897 OCSPRevocationStatus::GOOD},
10898
10899 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10900 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
10901 {SpawnedTestServer::SSLOptions::OCSP_OK,
10902 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10903 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10904 OCSPVerifyResult::PROVIDED,
10905 true,
10906 OCSPRevocationStatus::GOOD},
10907
10908 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10909 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
10910 {SpawnedTestServer::SSLOptions::OCSP_OK,
10911 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
10912 {SpawnedTestServer::SSLOptions::OCSP_OK,
10913 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10914 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10915 OCSPVerifyResult::INVALID_DATE,
10916 false,
10917 OCSPRevocationStatus::UNKNOWN},
10918
10919 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10920 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10921 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10922 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10923 {SpawnedTestServer::SSLOptions::OCSP_OK,
10924 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10925 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10926 OCSPVerifyResult::PROVIDED,
10927 true,
10928 OCSPRevocationStatus::REVOKED},
10929
10930 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10931 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10932 {SpawnedTestServer::SSLOptions::OCSP_OK,
10933 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10934 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10935 OCSPVerifyResult::PROVIDED,
10936 true,
10937 OCSPRevocationStatus::UNKNOWN},
10938
10939 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10940 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10941 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10942 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
10943 {SpawnedTestServer::SSLOptions::OCSP_OK,
10944 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10945 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10946 OCSPVerifyResult::PROVIDED,
10947 true,
10948 OCSPRevocationStatus::UNKNOWN},
10949
10950 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10951 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10952 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10953 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10954 false,
10955 OCSPRevocationStatus::UNKNOWN},
10956
10957 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10958 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10959 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10960 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10961 false,
10962 OCSPRevocationStatus::UNKNOWN},
10963
10964};
10965
10966class HTTPSOCSPVerifyTest
10967 : public HTTPSOCSPTest,
10968 public testing::WithParamInterface<OCSPVerifyTestData> {};
10969
10970TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
10971 SpawnedTestServer::SSLOptions ssl_options(
10972 SpawnedTestServer::SSLOptions::CERT_AUTO);
10973 OCSPVerifyTestData test = GetParam();
10974
10975 ssl_options.ocsp_responses = test.ocsp_responses;
10976 ssl_options.ocsp_produced = test.ocsp_produced;
10977 ssl_options.staple_ocsp_response = true;
10978
10979 SSLInfo ssl_info;
10980 OCSPErrorTestDelegate delegate;
10981 ASSERT_NO_FATAL_FAILURE(
10982 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
10983
10984 // The SSLInfo must be extracted from |delegate| on error, due to how
10985 // URLRequest caches certificate errors.
10986 if (delegate.have_certificate_errors()) {
10987 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
10988 ssl_info = delegate.ssl_info();
10989 }
10990
10991 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
10992
10993 if (test.has_revocation_status)
10994 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
10995}
10996
10997INSTANTIATE_TEST_CASE_P(OCSPVerify,
10998 HTTPSOCSPVerifyTest,
10999 testing::ValuesIn(kOCSPVerifyData));
11000
mattm0b12a6f2016-11-29 19:57:1611001static bool SystemSupportsAIA() {
11002#if defined(OS_ANDROID)
11003 return false;
11004#else
11005 return true;
11006#endif
11007}
11008
11009class HTTPSAIATest : public HTTPSOCSPTest {
11010 public:
11011 void SetupContext() override {
11012 context_.set_ssl_config_service(new TestSSLConfigService(
11013 false /* check for EV */, false /* online revocation checking */,
11014 false /* require rev. checking for local anchors */,
11015 false /* token binding enabled */));
11016 }
11017};
11018
11019TEST_F(HTTPSAIATest, AIAFetching) {
11020 SpawnedTestServer::SSLOptions ssl_options(
11021 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
11022 SpawnedTestServer test_server(
11023 SpawnedTestServer::TYPE_HTTPS, ssl_options,
11024 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11025 ASSERT_TRUE(test_server.Start());
11026
11027 TestDelegate d;
11028 d.set_allow_certificate_errors(true);
11029 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611030 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11031 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1611032
11033 r->Start();
11034 EXPECT_TRUE(r->is_pending());
11035
11036 base::RunLoop().Run();
11037
11038 EXPECT_EQ(1, d.response_started_count());
11039
11040 CertStatus cert_status = r->ssl_info().cert_status;
11041 if (SystemSupportsAIA()) {
11042 EXPECT_EQ(OK, d.request_status());
11043 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11044 ASSERT_TRUE(r->ssl_info().cert);
11045 EXPECT_EQ(2u, r->ssl_info().cert->GetIntermediateCertificates().size());
11046 } else {
11047 EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID,
11048 cert_status & CERT_STATUS_ALL_ERRORS);
11049 }
11050 ASSERT_TRUE(r->ssl_info().unverified_cert);
11051 EXPECT_EQ(
11052 0u, r->ssl_info().unverified_cert->GetIntermediateCertificates().size());
11053}
11054
[email protected]3a86a712013-07-30 07:16:2011055class HTTPSHardFailTest : public HTTPSOCSPTest {
11056 protected:
rsleevid6de8302016-06-21 01:33:2011057 void SetupContext() override {
11058 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1411059 false /* check for EV */, false /* online revocation checking */,
11060 true /* require rev. checking for local
11061 anchors */,
11062 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:2011063 }
11064};
11065
[email protected]3a86a712013-07-30 07:16:2011066TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
11067 if (!SystemSupportsOCSP()) {
11068 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11069 return;
11070 }
11071
11072 if (!SystemSupportsHardFailRevocationChecking()) {
11073 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
11074 << "revocation checking";
11075 return;
11076 }
11077
11078 SpawnedTestServer::SSLOptions ssl_options(
11079 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811080 ssl_options.ocsp_status =
11081 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2011082
11083 CertStatus cert_status;
11084 DoConnection(ssl_options, &cert_status);
11085
11086 EXPECT_EQ(CERT_STATUS_REVOKED,
11087 cert_status & CERT_STATUS_REVOKED);
11088
11089 // Without a positive OCSP response, we shouldn't show the EV status.
11090 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11091}
11092
[email protected]a13234c2012-03-20 21:45:0211093class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
11094 protected:
rsleevid6de8302016-06-21 01:33:2011095 void SetupContext() override {
11096 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1411097 true /* check for EV */, false /* online revocation checking */,
11098 false /* require rev. checking for local
11099 anchors */,
11100 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0211101 }
11102};
11103
11104TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
11105 if (!SystemSupportsOCSP()) {
11106 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11107 return;
11108 }
11109
[email protected]ce7d0cbc2013-05-03 18:57:2211110 SpawnedTestServer::SSLOptions ssl_options(
11111 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811112 ssl_options.ocsp_status =
11113 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0211114 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
11115
[email protected]924e9f92012-12-16 22:00:5311116 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211117 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211118
mattmaf868e72016-09-23 23:25:2011119 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211120 cert_status & CERT_STATUS_ALL_ERRORS);
11121
11122 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811123 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11124 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211125}
11126
[email protected]be0fff62013-08-29 23:37:4811127TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
11128 if (!SystemSupportsOCSP()) {
11129 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11130 return;
11131 }
11132
11133 SpawnedTestServer::SSLOptions ssl_options(
11134 SpawnedTestServer::SSLOptions::CERT_AUTO);
11135 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11136 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
11137
11138 CertStatus cert_status;
11139 DoConnection(ssl_options, &cert_status);
11140
mattm1a282f52016-11-10 21:49:4211141// Currently only works for Windows and OS X. When using NSS, it's not
11142// possible to determine whether the check failed because of actual
11143// revocation or because there was an OCSP failure.
11144#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4811145 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11146#else
11147 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11148#endif
11149
11150 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11151 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11152 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11153}
11154
[email protected]a13234c2012-03-20 21:45:0211155TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
11156 if (!SystemSupportsOCSP()) {
11157 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11158 return;
11159 }
11160
[email protected]ce7d0cbc2013-05-03 18:57:2211161 SpawnedTestServer::SSLOptions ssl_options(
11162 SpawnedTestServer::SSLOptions::CERT_AUTO);
11163 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0211164 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
11165
11166 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211167 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211168
11169 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11170
11171 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11172 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0811173 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11174 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211175}
11176
11177TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
11178 if (!SystemSupportsOCSP()) {
11179 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11180 return;
11181 }
11182
[email protected]ce7d0cbc2013-05-03 18:57:2211183 SpawnedTestServer::SSLOptions ssl_options(
11184 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811185 ssl_options.ocsp_status =
11186 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0211187 SSLConfigService::SetCRLSet(
11188 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
11189
11190 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211191 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211192
mattmaf868e72016-09-23 23:25:2011193 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211194 cert_status & CERT_STATUS_ALL_ERRORS);
11195
11196 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811197 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11198 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211199}
11200
[email protected]51523f52013-07-31 21:57:2811201TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
11202 if (!SystemSupportsOCSP()) {
11203 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11204 return;
11205 }
11206
11207 SpawnedTestServer::SSLOptions ssl_options(
11208 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811209 ssl_options.ocsp_status =
11210 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]51523f52013-07-31 21:57:2811211 SSLConfigService::SetCRLSet(
11212 scoped_refptr<CRLSet>(CRLSet::ForTesting(
11213 false, &kOCSPTestCertSPKI, "")));
11214
11215 CertStatus cert_status;
11216 DoConnection(ssl_options, &cert_status);
11217
11218 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
11219 // revocation check for EV.
11220 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11221 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11222 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11223 EXPECT_FALSE(
11224 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11225}
11226
11227TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
11228 if (!SystemSupportsOCSP()) {
11229 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11230 return;
11231 }
11232
[email protected]ce7d0cbc2013-05-03 18:57:2211233 SpawnedTestServer::SSLOptions ssl_options(
11234 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811235 ssl_options.ocsp_status =
11236 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0211237 SSLConfigService::SetCRLSet(
11238 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
11239
[email protected]51523f52013-07-31 21:57:2811240 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1211241 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211242
[email protected]51523f52013-07-31 21:57:2811243 // Even with a fresh CRLSet, we should still do online revocation checks when
11244 // the certificate chain isn't covered by the CRLSet, which it isn't in this
11245 // test.
mattmaf868e72016-09-23 23:25:2011246 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2811247 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0211248
[email protected]51523f52013-07-31 21:57:2811249 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0211250 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2811251 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211252}
11253
[email protected]b6f2de32012-08-17 04:35:0811254TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
11255 // Test that when EV verification is requested, but online revocation
11256 // checking is disabled, and the leaf certificate is not in fact EV, that
11257 // no revocation checking actually happens.
11258 if (!SystemSupportsOCSP()) {
11259 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11260 return;
11261 }
11262
11263 // Unmark the certificate's OID as EV, which should disable revocation
11264 // checking (as per the user preference)
11265 ev_test_policy_.reset();
11266
[email protected]ce7d0cbc2013-05-03 18:57:2211267 SpawnedTestServer::SSLOptions ssl_options(
11268 SpawnedTestServer::SSLOptions::CERT_AUTO);
11269 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:0811270 SSLConfigService::SetCRLSet(
11271 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
11272
11273 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211274 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:0811275
11276 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11277
11278 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11279 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11280}
11281
[email protected]a13234c2012-03-20 21:45:0211282class HTTPSCRLSetTest : public HTTPSOCSPTest {
11283 protected:
rsleevid6de8302016-06-21 01:33:2011284 void SetupContext() override {
11285 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1411286 false /* check for EV */, false /* online revocation checking */,
11287 false /* require rev. checking for local
11288 anchors */,
11289 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0211290 }
11291};
11292
11293TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2211294 SpawnedTestServer::SSLOptions ssl_options(
11295 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811296 ssl_options.ocsp_status =
11297 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0211298 SSLConfigService::SetCRLSet(
11299 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
11300
[email protected]924e9f92012-12-16 22:00:5311301 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211302 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211303
11304 // If we're not trying EV verification then, even if the CRLSet has expired,
11305 // we don't fall back to online revocation checks.
11306 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11307 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11308 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11309}
[email protected]51523f52013-07-31 21:57:2811310
11311TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:3011312#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2811313 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11314 return;
11315#endif
11316
11317 SpawnedTestServer::SSLOptions ssl_options(
11318 SpawnedTestServer::SSLOptions::CERT_AUTO);
11319 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11320 ssl_options.cert_serial = 10;
11321 SSLConfigService::SetCRLSet(
11322 scoped_refptr<CRLSet>(CRLSet::ForTesting(
11323 false, &kOCSPTestCertSPKI, "\x0a")));
11324
11325 CertStatus cert_status = 0;
11326 DoConnection(ssl_options, &cert_status);
11327
11328 // If the certificate is recorded as revoked in the CRLSet, that should be
11329 // reflected without online revocation checking.
11330 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11331 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11332 EXPECT_FALSE(
11333 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11334}
[email protected]316c1e5e2012-09-12 15:17:4411335#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2711336
brettwa1228ebb2016-10-28 03:51:3411337#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:4711338// These tests aren't passing on Android. Either the RemoteTestServer isn't
11339// starting up successfully, or it can't access the test files.
11340// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3111341class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1111342 public:
[email protected]d9fca99a2012-02-24 16:16:2011343 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0511344 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5511345 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4711346 // Can't use |default_context_|'s HostResolver to set up the
11347 // FTPTransactionFactory because it hasn't been created yet.
11348 default_context_.set_host_resolver(&host_resolver_);
11349 }
11350
11351 // URLRequestTest interface:
11352 void SetUpFactory() override {
11353 // Add FTP support to the default URLRequestContext.
11354 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0511355 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4711356 }
11357
11358 std::string GetTestFileContents() {
11359 base::FilePath path;
11360 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
11361 path = path.Append(kTestFilePath);
11362 path = path.AppendASCII(kFtpTestFile);
11363 std::string contents;
11364 EXPECT_TRUE(base::ReadFileToString(path, &contents));
11365 return contents;
[email protected]95409e12010-08-17 20:07:1111366 }
11367
[email protected]b89ca032009-08-31 21:41:3111368 protected:
mmenkecd4c7532016-10-19 18:36:0511369 // Note that this is destroyed before the FtpProtocolHandler that references
11370 // it, which is owned by the parent class. Since no requests are made during
11371 // teardown, this works, though it's not great.
mmenke9f2ec60c2015-06-01 20:59:4711372 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4711373
tommycli59a63432015-11-06 00:10:5511374 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3111375};
11376
[email protected]d2a133182012-08-05 16:44:0811377// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0911378TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0811379 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0811380
11381 TestDelegate d;
11382 {
rhalavatib7bd7c792017-04-27 05:25:1611383 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11384 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911385 r->Start();
11386 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0811387
[email protected]255620da2013-08-19 13:14:2911388 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:0811389
[email protected]f7022f32014-08-21 16:32:1911390 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5011391 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0811392 }
11393}
11394
mmenke9f2ec60c2015-06-01 20:59:4711395TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5511396 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111397
[email protected]a25e90e2009-09-09 17:05:3711398 TestDelegate d;
11399 {
danakj8522a25b2016-04-16 00:17:3611400 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611401 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
11402 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911403 r->Start();
11404 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711405
[email protected]255620da2013-08-19 13:14:2911406 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:3711407
[email protected]f7022f32014-08-21 16:32:1911408 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711409 EXPECT_EQ(1, d.response_started_count());
11410 EXPECT_FALSE(d.received_data_before_response());
11411 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5511412 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911413 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511414 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911415 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:3711416 }
11417}
11418
mmenke9f2ec60c2015-06-01 20:59:4711419TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5511420 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111421
[email protected]dd265012009-01-08 20:45:2711422 TestDelegate d;
11423 {
danakj8522a25b2016-04-16 00:17:3611424 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611425 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
11426 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911427 r->Start();
11428 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711429
[email protected]255620da2013-08-19 13:14:2911430 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711431
[email protected]f7022f32014-08-21 16:32:1911432 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711433 EXPECT_EQ(1, d.response_started_count());
11434 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711435 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511436 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911437 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511438 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911439 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:2711440 }
11441}
11442
mmenke9f2ec60c2015-06-01 20:59:4711443TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5511444 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111445
[email protected]dd265012009-01-08 20:45:2711446 TestDelegate d;
11447 {
danakj8522a25b2016-04-16 00:17:3611448 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511449 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11450 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611451 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911452 r->Start();
11453 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711454
[email protected]255620da2013-08-19 13:14:2911455 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711456
[email protected]f7022f32014-08-21 16:32:1911457 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4711458 EXPECT_EQ(1, d.response_started_count());
11459 EXPECT_FALSE(d.received_data_before_response());
11460 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511461 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911462 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511463 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911464 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:2511465
11466 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1911467 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2511468 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2711469 }
11470}
11471
mmenke9f2ec60c2015-06-01 20:59:4711472TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5511473 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111474
[email protected]dd265012009-01-08 20:45:2711475 TestDelegate d;
11476 {
danakj8522a25b2016-04-16 00:17:3611477 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511478 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11479 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611480 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911481 r->Start();
11482 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711483
[email protected]255620da2013-08-19 13:14:2911484 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711485
[email protected]f7022f32014-08-21 16:32:1911486 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711487 EXPECT_EQ(1, d.response_started_count());
11488 EXPECT_FALSE(d.received_data_before_response());
11489 EXPECT_EQ(d.bytes_received(), 0);
11490 }
11491}
11492
mmenke9f2ec60c2015-06-01 20:59:4711493TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5511494 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111495
[email protected]8b8a197d2009-08-26 15:57:5811496 TestDelegate d;
11497 // Set correct login credentials. The delegate will be asked for them when
11498 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811499 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5811500 {
danakj8522a25b2016-04-16 00:17:3611501 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511502 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11503 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611504 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911505 r->Start();
11506 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811507
[email protected]255620da2013-08-19 13:14:2911508 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5811509
[email protected]f7022f32014-08-21 16:32:1911510 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811511 EXPECT_EQ(1, d.response_started_count());
11512 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711513 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5811514 }
11515}
11516
mmenke9f2ec60c2015-06-01 20:59:4711517TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5511518 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111519
[email protected]dd265012009-01-08 20:45:2711520 TestDelegate d;
11521 {
danakj8522a25b2016-04-16 00:17:3611522 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511523 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
11524 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611525 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911526 r->Start();
11527 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711528
[email protected]255620da2013-08-19 13:14:2911529 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711530
[email protected]f7022f32014-08-21 16:32:1911531 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711532 EXPECT_EQ(1, d.response_started_count());
11533 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711534 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2711535 }
11536}
[email protected]8b8a197d2009-08-26 15:57:5811537
mmenke9f2ec60c2015-06-01 20:59:4711538TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5511539 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111540
[email protected]8b8a197d2009-08-26 15:57:5811541 TestDelegate d;
11542 // Set correct login credentials. The delegate will be asked for them when
11543 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811544 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5811545 {
danakj8522a25b2016-04-16 00:17:3611546 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511547 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
11548 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611549 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911550 r->Start();
11551 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811552
[email protected]255620da2013-08-19 13:14:2911553 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5811554
[email protected]f7022f32014-08-21 16:32:1911555 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811556 EXPECT_EQ(1, d.response_started_count());
11557 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711558 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5811559 }
11560}
[email protected]60a3df52009-09-22 16:13:2411561
mmenke9f2ec60c2015-06-01 20:59:4711562TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5511563 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111564
danakj8522a25b2016-04-16 00:17:3611565 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2411566 {
11567 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3611568 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511569 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11570 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611571 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911572 r->Start();
11573 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411574
[email protected]255620da2013-08-19 13:14:2911575 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411576
[email protected]f7022f32014-08-21 16:32:1911577 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411578 EXPECT_EQ(1, d->response_started_count());
11579 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711580 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411581 }
11582
11583 d.reset(new TestDelegate);
11584 {
11585 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3611586 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611587 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
11588 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911589 r->Start();
11590 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411591
[email protected]255620da2013-08-19 13:14:2911592 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411593
[email protected]f7022f32014-08-21 16:32:1911594 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411595 EXPECT_EQ(1, d->response_started_count());
11596 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711597 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411598 }
11599}
11600
mmenke9f2ec60c2015-06-01 20:59:4711601TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5511602 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111603
danakj8522a25b2016-04-16 00:17:3611604 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2411605 // Set correct login credentials. The delegate will be asked for them when
11606 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811607 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2411608 {
danakj8522a25b2016-04-16 00:17:3611609 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511610 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11611 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611612 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911613 r->Start();
11614 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411615
[email protected]255620da2013-08-19 13:14:2911616 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411617
[email protected]f7022f32014-08-21 16:32:1911618 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411619 EXPECT_EQ(1, d->response_started_count());
11620 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711621 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411622 }
11623
11624 // Use a new delegate without explicit credentials. The cached ones should be
11625 // used.
11626 d.reset(new TestDelegate);
11627 {
11628 // Don't pass wrong credentials in the URL, they would override valid cached
11629 // ones.
danakj8522a25b2016-04-16 00:17:3611630 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611631 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
11632 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911633 r->Start();
11634 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411635
[email protected]255620da2013-08-19 13:14:2911636 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411637
[email protected]f7022f32014-08-21 16:32:1911638 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411639 EXPECT_EQ(1, d->response_started_count());
11640 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711641 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411642 }
11643}
ricea3a1c71f2016-06-17 10:05:2611644
11645TEST_F(URLRequestTestFTP, RawBodyBytes) {
11646 ASSERT_TRUE(ftp_test_server_.Start());
11647
11648 TestDelegate d;
11649 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611650 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
11651 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2611652 req->Start();
11653 base::RunLoop().Run();
11654
11655 EXPECT_EQ(6, req->GetRawBodyBytes());
11656}
11657
brettwa1228ebb2016-10-28 03:51:3411658#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5111659
ttuttlec0c828492015-05-15 01:25:5511660TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
11661 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1611662 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
11663 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5511664
11665 EXPECT_FALSE(req->response_info().network_accessed);
11666
11667 req->Start();
11668 base::RunLoop().Run();
11669
11670 EXPECT_EQ(1, default_network_delegate_.completed_requests());
11671 EXPECT_FALSE(req->response_info().network_accessed);
11672}
11673
11674TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
11675 MockHostResolver host_resolver;
11676 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
11677 TestURLRequestContext context(true);
11678 context.set_network_delegate(&network_delegate);
11679 context.set_host_resolver(&host_resolver);
11680 host_resolver.rules()->AddSimulatedFailure("*");
11681 context.Init();
11682
11683 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1611684 std::unique_ptr<URLRequest> req(
11685 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
11686 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5511687
11688 EXPECT_FALSE(req->response_info().network_accessed);
11689
11690 req->Start();
11691 base::RunLoop().Run();
11692 EXPECT_TRUE(req->response_info().network_accessed);
11693}
11694
mmenkeed0498b2015-12-08 23:20:4211695// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2211696// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4211697TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2211698 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611699 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611700 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
11701 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2211702
danakj8522a25b2016-04-16 00:17:3611703 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2211704 req.get(), &default_network_delegate_,
11705 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4211706 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
11707 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2211708
11709 req->Start();
11710 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2211711 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5011712 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2211713 EXPECT_EQ(0, d.received_redirect_count());
11714}
11715
Andrey Kosyakov83a6eee2017-08-14 19:20:0411716TEST_F(URLRequestTestHTTP, RequestHeadersCallback) {
11717 ASSERT_TRUE(http_test_server()->Start());
11718 TestURLRequestContext context;
11719 GURL url(http_test_server()->GetURL("/cachetime"));
11720 TestDelegate delegate;
11721 HttpRequestHeaders extra_headers;
11722 extra_headers.SetHeader("X-Foo", "bar");
11723
11724 {
11725 HttpRawRequestHeaders raw_headers;
11726 std::unique_ptr<URLRequest> r(context.CreateRequest(
11727 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11728 r->SetExtraRequestHeaders(extra_headers);
11729 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
11730 base::Unretained(&raw_headers)));
11731 r->Start();
11732 while (!delegate.response_started_count())
11733 base::RunLoop().RunUntilIdle();
11734 EXPECT_FALSE(raw_headers.headers().empty());
11735 std::string value;
11736 EXPECT_TRUE(raw_headers.FindHeaderForTest("X-Foo", &value));
11737 EXPECT_EQ("bar", value);
11738 EXPECT_TRUE(raw_headers.FindHeaderForTest("Accept-Encoding", &value));
11739 EXPECT_EQ("gzip, deflate", value);
11740 EXPECT_TRUE(raw_headers.FindHeaderForTest("Connection", &value));
11741 EXPECT_TRUE(raw_headers.FindHeaderForTest("Host", &value));
11742 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_headers.request_line());
11743 }
11744 {
11745 HttpRawRequestHeaders raw_headers;
11746 std::unique_ptr<URLRequest> r(context.CreateRequest(
11747 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11748 r->SetExtraRequestHeaders(extra_headers);
11749 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
11750 FAIL() << "Callback should not be called unless request is sent";
11751 }));
11752 r->Start();
11753 base::RunLoop().Run();
11754 EXPECT_TRUE(r->was_cached());
11755 EXPECT_TRUE(raw_headers.headers().empty());
11756 EXPECT_TRUE(raw_headers.request_line().empty());
11757 }
11758}
11759
11760TEST_F(URLRequestTestHTTP, RequestHeadersCallbackWithRedirect) {
11761 ASSERT_TRUE(http_test_server()->Start());
11762 HttpRawRequestHeaders raw_headers;
11763 TestURLRequestContext context;
11764 TestDelegate delegate;
11765 HttpRequestHeaders extra_headers;
11766 extra_headers.SetHeader("X-Foo", "bar");
11767 delegate.set_quit_on_redirect(true);
11768 GURL url(http_test_server()->GetURL("/redirect-test.html"));
11769 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11770 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11771 r->SetExtraRequestHeaders(extra_headers);
11772 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
11773 base::Unretained(&raw_headers)));
11774 r->Start();
11775 base::RunLoop().Run();
11776
11777 ASSERT_EQ(1, delegate.received_redirect_count());
11778 std::string value;
11779 EXPECT_TRUE(raw_headers.FindHeaderForTest("X-Foo", &value));
11780 EXPECT_EQ("bar", value);
11781 EXPECT_TRUE(raw_headers.FindHeaderForTest("Accept-Encoding", &value));
11782 EXPECT_EQ("gzip, deflate", value);
11783 EXPECT_EQ(1, delegate.received_redirect_count());
11784 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n", raw_headers.request_line());
11785
11786 raw_headers = HttpRawRequestHeaders();
11787 r->FollowDeferredRedirect();
11788 base::RunLoop().Run();
11789 EXPECT_TRUE(raw_headers.FindHeaderForTest("X-Foo", &value));
11790 EXPECT_EQ("bar", value);
11791 EXPECT_TRUE(raw_headers.FindHeaderForTest("Accept-Encoding", &value));
11792 EXPECT_EQ("gzip, deflate", value);
11793 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n", raw_headers.request_line());
11794}
11795
11796TEST_F(URLRequestTest, RequestHeadersCallbackConnectFailed) {
11797 TestDelegate request_delegate;
11798
11799 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11800 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
11801 TRAFFIC_ANNOTATION_FOR_TESTS));
11802 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
11803 FAIL() << "Callback should not be called unless request is sent";
11804 }));
11805 r->Start();
11806 base::RunLoop().Run();
11807 EXPECT_FALSE(r->is_pending());
11808}
11809
11810TEST_F(URLRequestTestHTTP, RequestHeadersCallbackAuthRetry) {
11811 ASSERT_TRUE(http_test_server()->Start());
11812 GURL url(http_test_server()->GetURL("/auth-basic"));
11813
11814 TestURLRequestContext context;
11815 TestDelegate delegate;
11816
11817 delegate.set_credentials(AuthCredentials(kUser, kSecret));
11818 HttpRequestHeaders extra_headers;
11819 extra_headers.SetHeader("X-Foo", "bar");
11820
11821 using HeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
11822 HeadersVector raw_headers;
11823
11824 std::unique_ptr<URLRequest> r(context.CreateRequest(
11825 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11826 r->SetExtraRequestHeaders(extra_headers);
11827 r->SetRequestHeadersCallback(base::Bind(
11828 [](HeadersVector* vec, HttpRawRequestHeaders headers) {
11829 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
11830 },
11831 &raw_headers));
11832 r->Start();
11833 base::RunLoop().Run();
11834 EXPECT_FALSE(r->is_pending());
11835 ASSERT_GE(raw_headers.size(), 2u);
11836 std::string value;
11837 EXPECT_FALSE(raw_headers[0]->FindHeaderForTest("Authorization", &value));
11838 EXPECT_TRUE(raw_headers[0]->FindHeaderForTest("X-Foo", &value));
11839 EXPECT_EQ("bar", value);
11840 EXPECT_TRUE(raw_headers[1]->FindHeaderForTest("Authorization", &value));
11841 EXPECT_TRUE(raw_headers[1]->FindHeaderForTest("X-Foo", &value));
11842 EXPECT_EQ("bar", value);
11843}
11844
11845TEST_F(URLRequestTest, RequestHeadersCallbackNonHTTP) {
11846 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
11847 TestDelegate d;
11848 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11849 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
11850 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
11851 FAIL() << "Callback should not be called unless request is sent";
11852 }));
11853 r->Start();
11854 base::RunLoop().Run();
11855 EXPECT_FALSE(r->is_pending());
11856}
11857
[email protected]7461a402011-03-24 23:19:5111858} // namespace net